Skip to main content

etchdns/
dns_parser.rs

1use byteorder::{BigEndian, ByteOrder};
2use log::debug;
3use std::str;
4
5use crate::errors::{DnsError, DnsResult};
6
7// DNS packet constants
8pub const DNS_PACKET_LEN_MIN: usize = 12; // Minimum size of a DNS packet (header only)
9pub const DNS_HEADER_SIZE: usize = DNS_PACKET_LEN_MIN; // Size of the DNS header
10pub const DNS_MAX_PACKET_SIZE: usize = 0x1600; // Maximum size of a DNS packet
11pub const DNS_MAX_HOSTNAME_SIZE: usize = 256; // Maximum size of a hostname
12pub const DNS_OFFSET_QUESTION: usize = DNS_HEADER_SIZE; // Offset to the question section
13pub const DNS_MAX_UDP_PACKET_SIZE: usize = 512; // Standard maximum UDP packet size (RFC 1035)
14
15// DNS record types
16pub const DNS_TYPE_A: u16 = 1;
17pub const DNS_TYPE_NS: u16 = 2;
18pub const DNS_TYPE_CNAME: u16 = 5;
19pub const DNS_TYPE_SOA: u16 = 6;
20pub const DNS_TYPE_PTR: u16 = 12;
21pub const DNS_TYPE_MX: u16 = 15;
22#[allow(dead_code)]
23pub const DNS_TYPE_TXT: u16 = 16;
24pub const DNS_TYPE_AAAA: u16 = 28;
25pub const DNS_TYPE_SRV: u16 = 33;
26pub const DNS_TYPE_OPT: u16 = 41;
27pub const DNS_TYPE_RRSIG: u16 = 46;
28pub const DNS_TYPE_ANY: u16 = 255;
29
30#[cfg(test)]
31pub(crate) const NEGATIVE_RESPONSE_WITH_SOA_TTL_3600_MINIMUM_60: &[u8] = &[
32    0x12, 0x34, 0x81, 0x83, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x07, b'e', b'x', b'a',
33    b'm', b'p', b'l', b'e', 0x03, b'c', b'o', b'm', 0x00, 0x00, 0x01, 0x00, 0x01, 0xc0, 0x0c, 0x00,
34    0x06, 0x00, 0x01, 0x00, 0x00, 0x0e, 0x10, 0x00, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
35    0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x3c,
36];
37
38// DNS classes
39pub const DNS_CLASS_IN: u16 = 1;
40pub const DNS_CLASS_CH: u16 = 3;
41pub const DNS_CLASS_ANY: u16 = 255;
42
43// DNSSEC related constants
44pub const DNS_FLAG_DO: u16 = 0x8000; // DNSSEC OK flag in OPT record
45
46// EDNS option codes
47pub const EDNS_OPTION_CLIENT_SUBNET: u16 = 8; // Client Subnet (RFC 7871)
48pub const EDNS_OPTION_COOKIE: u16 = 10; // DNS Cookies (RFC 7873)
49
50// DNS header flags
51const DNS_FLAGS_QR: u16 = 1u16 << 15; // Query/Response flag
52const DNS_FLAGS_AA: u16 = 1u16 << 10; // Authoritative Answer flag
53const DNS_FLAGS_TC: u16 = 1u16 << 9; // Truncation flag
54#[allow(dead_code)]
55const DNS_FLAGS_RD: u16 = 1u16 << 8; // Recursion Desired
56const DNS_FLAGS_RA: u16 = 1u16 << 7; // Recursion Available flag
57const DNS_FLAGS_CD: u16 = 1u16 << 4; // Checking Disabled (DNSSEC)
58#[allow(dead_code)]
59const DNS_FLAGS_AD: u16 = 1u16 << 5; // Authentic Data (DNSSEC)
60
61// DNS opcodes (in bits 11-14 of the flags field)
62pub const DNS_OPCODE_QUERY: u8 = 0; // Standard query
63#[allow(dead_code)]
64pub const DNS_OPCODE_IQUERY: u8 = 1; // Inverse query
65#[allow(dead_code)]
66pub const DNS_OPCODE_STATUS: u8 = 2; // Server status request
67#[allow(dead_code)]
68pub const DNS_OPCODE_NOTIFY: u8 = 4; // Zone change notification
69#[allow(dead_code)]
70pub const DNS_OPCODE_UPDATE: u8 = 5; // Dynamic update
71
72/// Checks that a DNS packet looks valid, and returns the length of the message in it.
73///
74/// Some clients add extra bytes after the last record.
75/// They are allowed, but must be cut off before changing the message, or they could end up
76/// being read as records.
77pub fn validate_dns_packet(packet: &[u8]) -> DnsResult<usize> {
78    // Check minimum packet size
79    if packet.len() < DNS_HEADER_SIZE {
80        return Err(DnsError::PacketTooShort { offset: 0 });
81    }
82
83    // Check maximum packet size
84    if packet.len() > DNS_MAX_PACKET_SIZE {
85        return Err(DnsError::PacketTooLarge {
86            size: packet.len(),
87            max_size: DNS_MAX_PACKET_SIZE,
88        });
89    }
90
91    // Check opcode - we only support standard queries (opcode 0)
92    if !is_response(packet) {
93        let op = opcode(packet);
94        if op != DNS_OPCODE_QUERY {
95            return Err(DnsError::UnsupportedOperation(format!(
96                "Unsupported opcode: {op}"
97            )));
98        }
99    }
100
101    // Check that we have at least one question
102    let qd_count = qdcount(packet);
103    if qd_count == 0 {
104        return Err(DnsError::InvalidPacket(
105            "No questions in packet".to_string(),
106        ));
107    }
108
109    // For standard DNS queries, we typically expect exactly one question
110    if qd_count > 1 {
111        return Err(DnsError::InvalidPacket(
112            "Too many questions in packet".to_string(),
113        ));
114    }
115
116    // Validate the counts make sense for the packet size
117    let (an_count, ns_count, ar_count) = (ancount(packet), nscount(packet), arcount(packet));
118
119    // Try to parse the question section
120    let mut offset = DNS_HEADER_SIZE;
121
122    // Validate each question section
123    for _ in 0..qd_count {
124        // Validate the question name
125        offset = match skip_name(packet, offset) {
126            Ok(new_offset) => new_offset,
127            Err(e) => {
128                return Err(DnsError::InvalidQuestion(format!(
129                    "Invalid question name: {e}"
130                )));
131            }
132        };
133
134        // Ensure there's enough space for QTYPE and QCLASS (4 bytes)
135        if packet.len() < offset + 4 {
136            return Err(DnsError::InvalidPacket(
137                "Packet too short for QTYPE and QCLASS".to_string(),
138            ));
139        }
140
141        // Read QTYPE and QCLASS
142        let qtype_end = offset.checked_add(2).ok_or_else(|| {
143            DnsError::InvalidPacket("Integer overflow calculating QTYPE offset".to_string())
144        })?;
145        let qclass_end = offset.checked_add(4).ok_or_else(|| {
146            DnsError::InvalidPacket("Integer overflow calculating QCLASS offset".to_string())
147        })?;
148        let _qtype = BigEndian::read_u16(&packet[offset..qtype_end]);
149        let qclass = BigEndian::read_u16(&packet[qtype_end..qclass_end]);
150
151        // Validate QCLASS (typically IN=1 or ANY=255)
152        if qclass != DNS_CLASS_IN && qclass != DNS_CLASS_ANY {
153            debug!("Unusual: DNS query with QCLASS={qclass}");
154        }
155
156        // Additional validation: extract the query name and validate it
157        match qname(packet) {
158            Ok(name) => {
159                if name.len() > DNS_MAX_HOSTNAME_SIZE {
160                    return Err(DnsError::DomainNameTooLong {
161                        length: name.len(),
162                        max_length: DNS_MAX_HOSTNAME_SIZE,
163                    });
164                }
165
166                // Validate domain name characters
167                let labels: Vec<&[u8]> = name.split(|&c| c == b'.').collect();
168                for label in labels {
169                    if label.is_empty() {
170                        // Skip empty labels (like the root label) in normal domain names
171                        // But if it's between other labels (like "example..com"), that's an error
172                        if !name.starts_with(b".") && !name.ends_with(b".") && name.len() > 1 {
173                            return Err(DnsError::EmptyLabel);
174                        }
175                        continue;
176                    }
177
178                    // Check label length
179                    if label.len() > 63 {
180                        return Err(DnsError::LabelTooLong {
181                            length: label.len(),
182                        });
183                    }
184
185                    // Validate each character in the label
186                    for (i, &c) in label.iter().enumerate() {
187                        if !is_valid_domain_name_char(c, i, label.len()) {
188                            let label_str = match std::str::from_utf8(label) {
189                                Ok(s) => s.to_string(),
190                                Err(_) => format!("{label:?}"),
191                            };
192
193                            return Err(DnsError::InvalidDomainNameCharacter {
194                                character: c as char,
195                                position: i,
196                                label: label_str,
197                            });
198                        }
199                    }
200                }
201            }
202            Err(e) => {
203                return Err(DnsError::InvalidQuestion(format!(
204                    "Failed to extract query name: {e}"
205                )));
206            }
207        }
208
209        offset = offset.checked_add(4).ok_or_else(|| {
210            DnsError::InvalidPacket("Integer overflow advancing past QTYPE/QCLASS".to_string())
211        })?;
212    }
213
214    // Try to validate the answer, authority, and additional sections
215    // Check for potential overflow when calculating total_rr_count
216    let an_count_usize = an_count as usize;
217    let ns_count_usize = ns_count as usize;
218    let ar_count_usize = ar_count as usize;
219
220    // Check for overflow when adding up the counts
221    let total_rr_count = match an_count_usize.checked_add(ns_count_usize) {
222        Some(count) => match count.checked_add(ar_count_usize) {
223            Some(total) => total,
224            None => {
225                return Err(DnsError::InvalidPacket(
226                    "Integer overflow in resource record count calculation".to_string(),
227                ));
228            }
229        },
230        None => {
231            return Err(DnsError::InvalidPacket(
232                "Integer overflow in resource record count calculation".to_string(),
233            ));
234        }
235    };
236
237    // Validate against maximum sensible number of records
238    const MAX_SENSIBLE_RR_COUNT: usize = 1000;
239    if total_rr_count > MAX_SENSIBLE_RR_COUNT {
240        return Err(DnsError::InvalidPacket(format!(
241            "Excessive resource record count: {total_rr_count} (max {MAX_SENSIBLE_RR_COUNT})"
242        )));
243    }
244
245    if total_rr_count > 0 {
246        match traverse_rrs(packet, offset, total_rr_count, |rr_offset| {
247            // Validate record type
248            // Make sure we have at least 2 bytes to read at rr_offset
249            if packet.len() < rr_offset + 2 {
250                return Err(DnsError::PacketTooShort { offset: rr_offset });
251            }
252            let _rr_type = BigEndian::read_u16(&packet[rr_offset..rr_offset + 2]);
253
254            // Validate TTL - make sure we have at least 8 bytes at rr_offset
255            if packet.len() < rr_offset + 8 {
256                return Err(DnsError::PacketTooShort { offset: rr_offset });
257            }
258            let ttl = BigEndian::read_u32(&packet[rr_offset + 4..rr_offset + 8]);
259            if ttl > 604800 {
260                // 7 days in seconds
261                debug!("Unusual: DNS record with TTL > 7 days: {ttl} seconds");
262            }
263
264            // Validate RDLENGTH - make sure we have at least 10 bytes at rr_offset
265            if packet.len() < rr_offset + 10 {
266                return Err(DnsError::PacketTooShort { offset: rr_offset });
267            }
268            let rdlength = BigEndian::read_u16(&packet[rr_offset + 8..rr_offset + 10]) as usize;
269
270            // Check for potential overflow when calculating rr_offset + 10 + rdlength
271            let rr_data_end = match rr_offset.checked_add(10) {
272                Some(offset_plus_10) => match offset_plus_10.checked_add(rdlength) {
273                    Some(end_offset) => end_offset,
274                    None => {
275                        return Err(DnsError::InvalidRecord(
276                            "Integer overflow calculating record data bounds".to_string(),
277                        ));
278                    }
279                },
280                None => {
281                    return Err(DnsError::InvalidRecord(
282                        "Integer overflow calculating record data bounds".to_string(),
283                    ));
284                }
285            };
286
287            if packet.len() < rr_data_end {
288                return Err(DnsError::InvalidRecord(format!(
289                    "Record data length ({rdlength}) exceeds packet bounds"
290                )));
291            }
292
293            Ok(())
294        }) {
295            Ok(_) => (),
296            Err(e) => {
297                return Err(DnsError::InvalidRecord(format!(
298                    "Invalid resource record: {e}"
299                )));
300            }
301        }
302    }
303
304    let additional_offset = traverse_rrs(
305        packet,
306        offset,
307        an_count as usize + ns_count as usize,
308        |_| Ok(()),
309    )?;
310    let message_len = validate_edns_records(packet, additional_offset, ar_count as usize)?;
311
312    // Check EDNS version if OPT record is present
313    if let Some(edns_version) = extract_edns_version(packet)?
314        && edns_version != 0
315    {
316        return Err(DnsError::UnsupportedEdnsVersion {
317            version: edns_version,
318        });
319    }
320
321    Ok(message_len)
322}
323
324fn validate_edns_records(packet: &[u8], mut offset: usize, arcount: usize) -> DnsResult<usize> {
325    let mut found_opt = false;
326
327    for _ in 0..arcount {
328        let owner_offset = offset;
329        let rr_offset = skip_name(packet, owner_offset)?;
330        if packet.len().saturating_sub(rr_offset) < 10 {
331            return Err(DnsError::PacketTooShort { offset: rr_offset });
332        }
333
334        if BigEndian::read_u16(&packet[rr_offset..rr_offset + 2]) == DNS_TYPE_OPT {
335            if packet[owner_offset] != 0 {
336                return Err(DnsError::InvalidEdns(
337                    "OPT record owner must be the root name".to_string(),
338                ));
339            }
340            if found_opt {
341                return Err(DnsError::InvalidEdns("Duplicate OPT RR found".to_string()));
342            }
343            found_opt = true;
344        }
345
346        offset = traverse_rrs(packet, owner_offset, 1, |_| Ok(()))?;
347    }
348
349    Ok(offset)
350}
351
352/// Returns the transaction ID from the DNS packet
353#[inline]
354pub fn tid(packet: &[u8]) -> u16 {
355    if packet.len() < 2 {
356        return 0; // Return 0 for malformed packets
357    }
358    BigEndian::read_u16(&packet[0..2])
359}
360
361/// Returns the number of questions in the DNS packet
362#[inline]
363pub fn qdcount(packet: &[u8]) -> u16 {
364    if packet.len() < 6 {
365        return 0; // Return 0 for malformed packets
366    }
367    BigEndian::read_u16(&packet[4..6])
368}
369
370/// Returns the number of answer records in the DNS packet
371#[inline]
372pub fn ancount(packet: &[u8]) -> u16 {
373    if packet.len() < 8 {
374        return 0; // Return 0 for malformed packets
375    }
376    BigEndian::read_u16(&packet[6..8])
377}
378
379/// Returns the number of authority records in the DNS packet
380#[inline]
381pub fn nscount(packet: &[u8]) -> u16 {
382    if packet.len() < 10 {
383        return 0; // Return 0 for malformed packets
384    }
385    BigEndian::read_u16(&packet[8..10])
386}
387
388/// Returns the number of additional records in the DNS packet
389#[inline]
390pub fn arcount(packet: &[u8]) -> u16 {
391    if packet.len() < DNS_PACKET_LEN_MIN {
392        return 0; // Return 0 for malformed packets
393    }
394    BigEndian::read_u16(&packet[10..DNS_PACKET_LEN_MIN])
395}
396
397/// Returns the response code from the DNS packet
398#[inline]
399pub fn rcode(packet: &[u8]) -> u8 {
400    if packet.len() < 4 {
401        return 2; // Return SERVFAIL (2) for truncated packets
402    }
403    packet[3] & 0x0F
404}
405
406/// Checks if the packet is a response
407#[inline]
408pub fn is_response(packet: &[u8]) -> bool {
409    if packet.len() < 4 {
410        return false; // Not a response if packet is too short
411    }
412    (BigEndian::read_u16(&packet[2..4]) & DNS_FLAGS_QR) == DNS_FLAGS_QR
413}
414
415/// Returns the opcode from the DNS packet
416#[inline]
417pub fn opcode(packet: &[u8]) -> u8 {
418    if packet.len() < 3 {
419        return 0; // Return standard query (0) for malformed packets
420    }
421    (packet[2] >> 3) & 0x0F
422}
423
424/// Checks if the packet is a standard query
425#[inline]
426#[allow(dead_code)]
427pub fn is_standard_query(packet: &[u8]) -> bool {
428    !is_response(packet) && opcode(packet) == DNS_OPCODE_QUERY
429}
430
431/// Checks if the packet has the TC (truncated) bit set
432#[inline]
433pub fn is_truncated(packet: &[u8]) -> bool {
434    if packet.len() < 4 {
435        return false; // Not truncated if packet is too short
436    }
437    (BigEndian::read_u16(&packet[2..4]) & DNS_FLAGS_TC) == DNS_FLAGS_TC
438}
439
440/// Checks if DNSSEC is requested (either DO bit set or CD bit set)
441#[allow(dead_code)]
442pub fn is_dnssec_requested(packet: &[u8]) -> DnsResult<bool> {
443    if packet.len() < 4 {
444        return Err(DnsError::PacketTooShort { offset: 0 });
445    }
446
447    if is_checking_disabled(packet) {
448        return Ok(true);
449    }
450
451    is_dnssec_ok(packet)
452}
453
454/// Checks whether the DNSSEC OK bit is set in an OPT record.
455pub fn is_dnssec_ok(packet: &[u8]) -> DnsResult<bool> {
456    if packet.len() < 4 {
457        return Err(DnsError::PacketTooShort { offset: 0 });
458    }
459
460    // Check for OPT record with DO bit set
461    let packet_len = packet.len();
462    if packet_len <= DNS_OFFSET_QUESTION {
463        return Err(DnsError::PacketTooShort { offset: 0 });
464    }
465
466    // Skip the question section
467    let mut offset = skip_name(packet, DNS_OFFSET_QUESTION)?;
468    if packet_len.saturating_sub(offset) < 4 {
469        return Err(DnsError::PacketTooShort { offset: 0 });
470    }
471    offset = offset.checked_add(4).ok_or_else(|| {
472        DnsError::InvalidPacket("Integer overflow skipping QTYPE/QCLASS".to_string())
473    })?; // Skip QTYPE and QCLASS
474
475    // Skip answer and authority sections
476    let (ancount, nscount, arcount) = (ancount(packet), nscount(packet), arcount(packet));
477    offset = traverse_rrs(packet, offset, ancount as usize + nscount as usize, |_| {
478        Ok(())
479    })?;
480
481    // Check additional records for OPT
482    let mut dnssec_requested = false;
483    traverse_rrs(packet, offset, arcount as usize, |offset| {
484        let qtype = BigEndian::read_u16(&packet[offset..]);
485        if qtype == DNS_TYPE_OPT {
486            // OPT record found, check DO bit in flags
487            let opt_flags = BigEndian::read_u16(&packet[offset + 6..]);
488            if (opt_flags & DNS_FLAG_DO) == DNS_FLAG_DO {
489                dnssec_requested = true;
490            }
491        }
492        Ok(())
493    })?;
494
495    Ok(dnssec_requested)
496}
497
498/// Checks whether recursion is desired.
499pub fn is_recursion_desired(packet: &[u8]) -> bool {
500    flags(packet) & DNS_FLAGS_RD != 0
501}
502
503/// Checks whether DNSSEC validation is disabled.
504pub fn is_checking_disabled(packet: &[u8]) -> bool {
505    flags(packet) & DNS_FLAGS_CD != 0
506}
507
508/// Checks whether the client is interested in authenticated-data signaling.
509pub fn is_authenticated_data_requested(packet: &[u8]) -> bool {
510    flags(packet) & DNS_FLAGS_AD != 0
511}
512
513/// Extracts the query name from a DNS packet
514#[allow(dead_code)]
515pub fn query_name(packet: &[u8]) -> DnsResult<String> {
516    let qname_bytes = qname(packet)?;
517
518    // Validate maximum length before conversion
519    if qname_bytes.len() > DNS_MAX_HOSTNAME_SIZE {
520        return Err(DnsError::DomainNameTooLong {
521            length: qname_bytes.len(),
522            max_length: DNS_MAX_HOSTNAME_SIZE,
523        });
524    }
525
526    let qname_str = match str::from_utf8(&qname_bytes) {
527        Ok(s) => s,
528        Err(_) => {
529            return Err(DnsError::InvalidDomainName(
530                "Invalid UTF-8 in query name".to_string(),
531            ));
532        }
533    };
534
535    // Check once more for DoS using large string allocations
536    if qname_str.len() > DNS_MAX_HOSTNAME_SIZE {
537        return Err(DnsError::DomainNameTooLong {
538            length: qname_str.len(),
539            max_length: DNS_MAX_HOSTNAME_SIZE,
540        });
541    }
542
543    Ok(qname_str.to_string())
544}
545
546/// Extracts the query type and class from a DNS packet
547pub fn query_type_class(packet: &[u8]) -> DnsResult<(u16, u16)> {
548    if packet.len() < DNS_HEADER_SIZE {
549        return Err(DnsError::PacketTooShort { offset: 0 });
550    }
551    if qdcount(packet) == 0 {
552        return Err(DnsError::InvalidPacket("No question".to_string()));
553    }
554
555    let offset = skip_name(packet, DNS_HEADER_SIZE)?;
556    if packet.len() - offset < 4 {
557        return Err(DnsError::PacketTooShort { offset: 0 });
558    }
559
560    let qtype = BigEndian::read_u16(&packet[offset..]);
561    let qclass = BigEndian::read_u16(&packet[offset + 2..]);
562
563    Ok((qtype, qclass))
564}
565
566/// Checks whether a DNS response carries the same question as a query.
567pub fn questions_match(query: &[u8], response: &[u8]) -> DnsResult<bool> {
568    if opcode(query) != opcode(response) {
569        return Ok(false);
570    }
571
572    let query_name = qname(query)?;
573    let response_name = qname(response)?;
574    let query_fields = query_type_class(query)?;
575    let response_fields = query_type_class(response)?;
576
577    Ok(query_name.eq_ignore_ascii_case(&response_name) && query_fields == response_fields)
578}
579
580/// Makes the response question use the same letter case as the query.
581///
582/// Cached and shared responses keep the case of the first client that asked.
583/// Resolvers that randomize the case of their queries reject them.
584///
585/// Fails if the names don't match.
586pub fn restore_qname_case(response: &mut [u8], query: &[u8]) -> DnsResult<()> {
587    if qdcount(response) == 0 {
588        return Ok(());
589    }
590    let query_name = &query[DNS_HEADER_SIZE..skip_name(query, DNS_HEADER_SIZE)?];
591    let response_name_end = skip_name(response, DNS_HEADER_SIZE)?;
592    let response_name = &mut response[DNS_HEADER_SIZE..response_name_end];
593    if !response_name.eq_ignore_ascii_case(query_name) {
594        return Err(DnsError::InvalidPacket(
595            "Response question doesn't match the query".to_string(),
596        ));
597    }
598    response_name.copy_from_slice(query_name);
599    Ok(())
600}
601
602/// Extracts the minimum TTL from all records in a DNS packet
603pub fn extract_min_ttl(packet: &[u8]) -> DnsResult<Option<u32>> {
604    let packet_len = packet.len();
605    if packet_len <= DNS_OFFSET_QUESTION {
606        return Err(DnsError::PacketTooShort { offset: 0 });
607    }
608    if packet_len > DNS_MAX_PACKET_SIZE {
609        return Err(DnsError::PacketTooLarge {
610            size: packet_len,
611            max_size: DNS_MAX_PACKET_SIZE,
612        });
613    }
614    if qdcount(packet) == 0 {
615        return Err(DnsError::InvalidPacket("No question".to_string()));
616    }
617
618    // Skip the question section
619    let mut offset = skip_name(packet, DNS_OFFSET_QUESTION)?;
620    if packet_len - offset < 4 {
621        return Err(DnsError::PacketTooShort { offset: 0 });
622    }
623    offset += 4; // Skip QTYPE and QCLASS
624
625    let (ancount, nscount, arcount) = (ancount(packet), nscount(packet), arcount(packet));
626    let total_rr_count = ancount as usize + nscount as usize + arcount as usize;
627
628    if total_rr_count == 0 {
629        return Ok(None);
630    }
631
632    let mut min_ttl: Option<u32> = None;
633
634    traverse_rrs(packet, offset, total_rr_count, |offset| {
635        let rr_type = BigEndian::read_u16(&packet[offset..offset + 2]);
636        let ttl = BigEndian::read_u32(&packet[offset + 4..offset + 8]);
637
638        // Ignore OPT records (type 41) when calculating minimum TTL
639        if rr_type != DNS_TYPE_OPT {
640            min_ttl = match min_ttl {
641                None => Some(ttl),
642                Some(current_min) => Some(std::cmp::min(current_min, ttl)),
643            };
644        }
645        Ok(())
646    })?;
647
648    Ok(min_ttl)
649}
650
651/// Returns how long a DNS response may be cached.
652///
653/// RFC 2308 limits negative responses to the smaller of the authority SOA record TTL and its MINIMUM field.
654pub fn extract_cache_ttl(packet: &[u8]) -> DnsResult<Option<u32>> {
655    let min_ttl = extract_min_ttl(packet)?;
656    if ancount(packet) != 0 {
657        return Ok(min_ttl);
658    }
659
660    let negative_ttl = extract_negative_ttl(packet)?;
661    Ok(match (min_ttl, negative_ttl) {
662        (Some(min_ttl), Some(negative_ttl)) => Some(min_ttl.min(negative_ttl)),
663        (Some(ttl), None) | (None, Some(ttl)) => Some(ttl),
664        (None, None) => None,
665    })
666}
667
668fn extract_negative_ttl(packet: &[u8]) -> DnsResult<Option<u32>> {
669    let packet_len = packet.len();
670    if packet_len <= DNS_OFFSET_QUESTION {
671        return Err(DnsError::PacketTooShort { offset: 0 });
672    }
673    if packet_len > DNS_MAX_PACKET_SIZE {
674        return Err(DnsError::PacketTooLarge {
675            size: packet_len,
676            max_size: DNS_MAX_PACKET_SIZE,
677        });
678    }
679    if qdcount(packet) == 0 {
680        return Err(DnsError::InvalidPacket("No question".to_string()));
681    }
682
683    let mut offset = skip_name(packet, DNS_OFFSET_QUESTION)?;
684    if packet_len.saturating_sub(offset) < 4 {
685        return Err(DnsError::PacketTooShort { offset });
686    }
687    offset += 4;
688
689    let mut negative_ttl = None;
690    traverse_rrs(packet, offset, nscount(packet) as usize, |rr_offset| {
691        if BigEndian::read_u16(&packet[rr_offset..rr_offset + 2]) != DNS_TYPE_SOA {
692            return Ok(());
693        }
694
695        let soa_ttl = BigEndian::read_u32(&packet[rr_offset + 4..rr_offset + 8]);
696        let rdlen = BigEndian::read_u16(&packet[rr_offset + 8..rr_offset + 10]) as usize;
697        let rdata_offset = rr_offset + 10;
698        let rdata_end = rdata_offset + rdlen;
699
700        let rname_offset = skip_name(packet, rdata_offset)?;
701        if rname_offset > rdata_end {
702            return Err(DnsError::InvalidRecord(
703                "SOA MNAME exceeds record data".to_string(),
704            ));
705        }
706        let fields_offset = skip_name(packet, rname_offset)?;
707        if fields_offset > rdata_end || rdata_end - fields_offset != 20 {
708            return Err(DnsError::InvalidRecord(
709                "SOA record must end with five 32-bit fields".to_string(),
710            ));
711        }
712
713        let minimum = BigEndian::read_u32(&packet[rdata_end - 4..rdata_end]);
714        let ttl = soa_ttl.min(minimum);
715        negative_ttl = Some(negative_ttl.map_or(ttl, |current: u32| current.min(ttl)));
716        Ok(())
717    })?;
718
719    Ok(negative_ttl)
720}
721
722/// Caps a negative response's SOA TTL so it ages with the cached answer.
723pub fn cap_negative_response_ttl(packet: &mut [u8], ttl: u32) -> DnsResult<()> {
724    let packet_len = packet.len();
725    if packet_len <= DNS_OFFSET_QUESTION {
726        return Err(DnsError::PacketTooShort { offset: 0 });
727    }
728    if packet_len > DNS_MAX_PACKET_SIZE {
729        return Err(DnsError::PacketTooLarge {
730            size: packet_len,
731            max_size: DNS_MAX_PACKET_SIZE,
732        });
733    }
734    if qdcount(packet) == 0 {
735        return Err(DnsError::InvalidPacket("No question".to_string()));
736    }
737    if ancount(packet) != 0 {
738        return Ok(());
739    }
740
741    let mut offset = skip_name(packet, DNS_OFFSET_QUESTION)?;
742    if packet_len.saturating_sub(offset) < 4 {
743        return Err(DnsError::PacketTooShort { offset });
744    }
745    offset += 4;
746
747    traverse_rrs_mut(
748        packet,
749        offset,
750        nscount(packet) as usize,
751        |packet, rr_offset| {
752            if BigEndian::read_u16(&packet[rr_offset..rr_offset + 2]) == DNS_TYPE_SOA {
753                let soa_ttl = BigEndian::read_u32(&packet[rr_offset + 4..rr_offset + 8]);
754                BigEndian::write_u32(&mut packet[rr_offset + 4..rr_offset + 8], soa_ttl.min(ttl));
755            }
756            Ok(())
757        },
758    )?;
759
760    Ok(())
761}
762
763/// Changes the TTL of all records in a DNS packet
764pub fn change_ttl(packet: &mut [u8], new_ttl: u32) -> DnsResult<()> {
765    let packet_len = packet.len();
766    if packet_len <= DNS_OFFSET_QUESTION {
767        return Err(DnsError::PacketTooShort { offset: 0 });
768    }
769    if packet_len > DNS_MAX_PACKET_SIZE {
770        return Err(DnsError::PacketTooLarge {
771            size: packet_len,
772            max_size: DNS_MAX_PACKET_SIZE,
773        });
774    }
775    if qdcount(packet) == 0 {
776        return Err(DnsError::InvalidPacket("No question".to_string()));
777    }
778
779    // Skip the question section
780    let mut offset = skip_name(packet, DNS_OFFSET_QUESTION)?;
781    if packet_len - offset < 4 {
782        return Err(DnsError::PacketTooShort { offset: 0 });
783    }
784    offset += 4; // Skip QTYPE and QCLASS
785
786    let (ancount, nscount, arcount) = (ancount(packet), nscount(packet), arcount(packet));
787    let total_rr_count = ancount as usize + nscount as usize + arcount as usize;
788
789    if total_rr_count == 0 {
790        return Ok(());
791    }
792
793    traverse_rrs_mut(packet, offset, total_rr_count, |packet, offset| {
794        let rr_type = BigEndian::read_u16(&packet[offset..offset + 2]);
795        if rr_type != DNS_TYPE_OPT {
796            BigEndian::write_u32(&mut packet[offset + 4..offset + 8], new_ttl);
797        }
798        Ok(())
799    })?;
800
801    Ok(())
802}
803
804/// Decrements each resource-record TTL by the elapsed cache time.
805pub fn decrement_ttl(packet: &mut [u8], elapsed: u32) -> DnsResult<()> {
806    let packet_len = packet.len();
807    if packet_len <= DNS_OFFSET_QUESTION {
808        return Err(DnsError::PacketTooShort { offset: 0 });
809    }
810    if packet_len > DNS_MAX_PACKET_SIZE {
811        return Err(DnsError::PacketTooLarge {
812            size: packet_len,
813            max_size: DNS_MAX_PACKET_SIZE,
814        });
815    }
816    if qdcount(packet) == 0 {
817        return Err(DnsError::InvalidPacket("No question".to_string()));
818    }
819
820    let mut offset = skip_name(packet, DNS_OFFSET_QUESTION)?;
821    if packet_len - offset < 4 {
822        return Err(DnsError::PacketTooShort { offset: 0 });
823    }
824    offset += 4;
825
826    let total_rr_count =
827        ancount(packet) as usize + nscount(packet) as usize + arcount(packet) as usize;
828    traverse_rrs_mut(packet, offset, total_rr_count, |packet, offset| {
829        let rr_type = BigEndian::read_u16(&packet[offset..offset + 2]);
830        if rr_type != DNS_TYPE_OPT {
831            let ttl = BigEndian::read_u32(&packet[offset + 4..offset + 8]);
832            BigEndian::write_u32(
833                &mut packet[offset + 4..offset + 8],
834                ttl.saturating_sub(elapsed),
835            );
836        }
837        Ok(())
838    })?;
839
840    Ok(())
841}
842
843// Helper functions
844
845/// Validates a single character in a domain name label
846///
847/// Allows the LDH (letters, digits, hyphens) set from RFC 1035/1123 plus
848/// a leading underscore per RFC 8552 for underscored labels used by SRV,
849/// DKIM, DMARC, TLSA and similar record types.
850fn is_valid_domain_name_char(c: u8, position: usize, label_len: usize) -> bool {
851    let is_letter = c.is_ascii_lowercase() || c.is_ascii_uppercase();
852    let is_digit = c.is_ascii_digit();
853    let is_hyphen = c == b'-';
854
855    // Leading underscore allowed per RFC 8552 (e.g., _sip._tcp.example.com)
856    if position == 0 {
857        return is_letter || is_digit || c == b'_';
858    }
859
860    // Last character must be a letter or digit
861    if position == label_len - 1 {
862        return is_letter || is_digit;
863    }
864
865    // Middle characters can be letters, digits, or hyphens
866    is_letter || is_digit || is_hyphen
867}
868
869// This function is now only used in validate_dns_packet
870
871/// Extracts the raw query name from a DNS packet
872pub fn qname(packet: &[u8]) -> DnsResult<Vec<u8>> {
873    let packet_len = packet.len();
874    if packet_len <= DNS_OFFSET_QUESTION {
875        return Err(DnsError::PacketTooShort { offset: 0 });
876    }
877    if qdcount(packet) == 0 {
878        return Err(DnsError::InvalidPacket("No question".to_string()));
879    }
880
881    let mut offset = DNS_HEADER_SIZE;
882    let mut qname = Vec::with_capacity(DNS_MAX_HOSTNAME_SIZE);
883
884    loop {
885        if offset >= packet_len {
886            return Err(DnsError::PacketTooShort { offset: 0 });
887        }
888        match packet[offset] as usize {
889            label_len if label_len & 0xc0 == 0xc0 => {
890                // Check if we have enough bytes for the compression pointer
891                if offset + 1 >= packet_len {
892                    return Err(DnsError::PacketTooShort { offset });
893                }
894
895                // Compression pointer - not expected in the query name
896                let second_byte = packet[offset + 1] as usize;
897                return Err(DnsError::InvalidCompressionPointer {
898                    offset,
899                    pointer: ((label_len & 0x3f) << 8) | second_byte,
900                    packet_size: packet_len,
901                });
902            }
903            0 => {
904                if qname.is_empty() {
905                    qname.push(b'.');
906                }
907                break;
908            }
909            label_len => {
910                if label_len >= 0x40 {
911                    return Err(DnsError::LabelTooLong { length: label_len });
912                }
913                if packet_len.saturating_sub(offset) <= 1 {
914                    return Err(DnsError::PacketTooShort { offset: 0 });
915                }
916                offset = offset.checked_add(1).ok_or_else(|| {
917                    DnsError::InvalidPacket(
918                        "Integer overflow advancing past label length byte".to_string(),
919                    )
920                })?;
921                if packet_len.saturating_sub(offset) < label_len {
922                    return Err(DnsError::PacketTooShort { offset: 0 });
923                }
924
925                if !qname.is_empty() {
926                    qname.push(b'.');
927                }
928
929                if qname.len() + label_len >= DNS_MAX_HOSTNAME_SIZE {
930                    return Err(DnsError::DomainNameTooLong {
931                        length: qname.len() + label_len,
932                        max_length: DNS_MAX_HOSTNAME_SIZE,
933                    });
934                }
935
936                let label_end = offset.checked_add(label_len).ok_or_else(|| {
937                    DnsError::InvalidPacket("Integer overflow calculating label end".to_string())
938                })?;
939                // Otherwise the single label "a.b" would look like the two labels "a" and "b"
940                if packet[offset..label_end].contains(&b'.') {
941                    return Err(DnsError::InvalidDomainName(
942                        "Label contains a dot".to_string(),
943                    ));
944                }
945                qname.extend_from_slice(&packet[offset..label_end]);
946                offset = label_end;
947            }
948        }
949    }
950
951    Ok(qname)
952}
953
954/// Skips over a domain name in a DNS packet
955fn skip_name(packet: &[u8], offset: usize) -> DnsResult<usize> {
956    let packet_len = packet.len();
957    if offset >= packet_len {
958        return Err(DnsError::PacketTooShort { offset: 0 });
959    }
960
961    let mut current_offset = offset;
962    let mut jumps = 0;
963    let mut total_name_len: usize = 0;
964    let mut result_offset_after_pointer: Option<usize> = None;
965
966    loop {
967        if current_offset >= packet_len {
968            return Err(DnsError::PacketTooShort {
969                offset: current_offset,
970            });
971        }
972        match packet[current_offset] as usize {
973            label_len if label_len & 0xc0 == 0xc0 => {
974                // Compression pointer
975                if packet_len - current_offset < 2 {
976                    return Err(DnsError::PacketTooShort {
977                        offset: current_offset,
978                    });
979                }
980                jumps += 1;
981                if jumps > 10 {
982                    return Err(DnsError::TooManyCompressionPointers { count: jumps });
983                }
984
985                // For the return value, we only advance 2 bytes for the first pointer,
986                // but still validate the pointer target below.
987                if jumps == 1 {
988                    // Use checked_add to prevent integer overflow
989                    let result_offset = match current_offset.checked_add(2) {
990                        Some(offset) => offset,
991                        None => {
992                            return Err(DnsError::InvalidCompressionPointer {
993                                offset: current_offset,
994                                pointer: 0,
995                                packet_size: packet_len,
996                            });
997                        }
998                    };
999
1000                    if result_offset > packet_len {
1001                        return Err(DnsError::PacketTooShort {
1002                            offset: current_offset,
1003                        });
1004                    }
1005                    result_offset_after_pointer = Some(result_offset);
1006                }
1007
1008                // Follow the pointer - safely extract second byte
1009                if current_offset + 1 >= packet_len {
1010                    return Err(DnsError::PacketTooShort {
1011                        offset: current_offset,
1012                    });
1013                }
1014
1015                // Calculate pointer value with overflow check
1016                let second_byte = packet[current_offset + 1] as usize;
1017                let first_part = (label_len & 0x3f) << 8;
1018                let pointer = match first_part.checked_add(second_byte) {
1019                    Some(ptr) => ptr,
1020                    None => {
1021                        return Err(DnsError::InvalidCompressionPointer {
1022                            offset: current_offset,
1023                            pointer: first_part,
1024                            packet_size: packet_len,
1025                        });
1026                    }
1027                };
1028                if pointer >= packet_len {
1029                    return Err(DnsError::InvalidCompressionPointer {
1030                        offset: current_offset,
1031                        pointer,
1032                        packet_size: packet_len,
1033                    });
1034                }
1035                if pointer >= current_offset {
1036                    return Err(DnsError::InvalidCompressionPointer {
1037                        offset: current_offset,
1038                        pointer,
1039                        packet_size: packet_len,
1040                    });
1041                }
1042                current_offset = pointer;
1043            }
1044            0 => {
1045                if total_name_len.saturating_add(1) > 255 {
1046                    return Err(DnsError::DomainNameTooLong {
1047                        length: total_name_len + 1,
1048                        max_length: 255,
1049                    });
1050                }
1051                // End of domain name
1052                current_offset = match current_offset.checked_add(1) {
1053                    Some(offset) => offset,
1054                    None => {
1055                        return Err(DnsError::PacketTooShort {
1056                            offset: current_offset,
1057                        });
1058                    }
1059                };
1060                break;
1061            }
1062            label_len => {
1063                // Regular label
1064                if label_len >= 0x40 {
1065                    return Err(DnsError::LabelTooLong { length: label_len });
1066                }
1067
1068                // Make sure we don't have integer underflow in the packet_len - current_offset check
1069                let remaining_bytes = if current_offset <= packet_len {
1070                    packet_len - current_offset
1071                } else {
1072                    return Err(DnsError::PacketTooShort {
1073                        offset: current_offset,
1074                    });
1075                };
1076
1077                // Check we have enough bytes for label_len
1078                if remaining_bytes <= label_len {
1079                    return Err(DnsError::PacketTooShort {
1080                        offset: current_offset,
1081                    });
1082                }
1083
1084                // Update the total name length with overflow check
1085                // Add 1 for the dot between labels (or the length byte in the packet)
1086                total_name_len = match label_len.checked_add(1) {
1087                    Some(len) => match total_name_len.checked_add(len) {
1088                        Some(total) => total,
1089                        None => {
1090                            return Err(DnsError::DomainNameTooLong {
1091                                length: u32::MAX as usize,
1092                                max_length: DNS_MAX_HOSTNAME_SIZE,
1093                            });
1094                        }
1095                    },
1096                    None => {
1097                        return Err(DnsError::DomainNameTooLong {
1098                            length: u32::MAX as usize,
1099                            max_length: DNS_MAX_HOSTNAME_SIZE,
1100                        });
1101                    }
1102                };
1103
1104                // Check if the total name length exceeds the maximum
1105                if total_name_len > DNS_MAX_HOSTNAME_SIZE {
1106                    return Err(DnsError::DomainNameTooLong {
1107                        length: total_name_len,
1108                        max_length: DNS_MAX_HOSTNAME_SIZE,
1109                    });
1110                }
1111
1112                // Safely advance the offset
1113                let label_plus_1 = match label_len.checked_add(1) {
1114                    Some(len) => len,
1115                    None => {
1116                        return Err(DnsError::LabelTooLong {
1117                            length: u32::MAX as usize,
1118                        });
1119                    }
1120                };
1121
1122                current_offset = match current_offset.checked_add(label_plus_1) {
1123                    Some(offset) => offset,
1124                    None => {
1125                        return Err(DnsError::PacketTooShort {
1126                            offset: current_offset,
1127                        });
1128                    }
1129                };
1130            }
1131        }
1132    }
1133
1134    Ok(result_offset_after_pointer.unwrap_or(current_offset))
1135}
1136
1137/// Traverses resource records in a DNS packet
1138/// Traverses resource records in a DNS packet and calls a callback for each record
1139///
1140/// This function iterates through a specified number of resource records in a DNS packet,
1141/// calling the provided callback function for each record. It handles domain name compression
1142/// and validates record boundaries.
1143///
1144/// # Arguments
1145///
1146/// * `packet` - The DNS packet data
1147/// * `offset` - Starting offset in the packet where the resource records begin
1148/// * `rrcount` - Number of resource records to traverse
1149/// * `callback` - Function to call for each resource record, receiving the offset of the record
1150///
1151/// # Returns
1152///
1153/// The final offset after traversing all records, or an error if packet validation fails
1154fn traverse_rrs<F>(
1155    packet: &[u8],
1156    mut offset: usize,
1157    rrcount: usize,
1158    mut callback: F,
1159) -> DnsResult<usize>
1160where
1161    F: FnMut(usize) -> DnsResult<()>,
1162{
1163    let packet_len = packet.len();
1164
1165    for _ in 0..rrcount {
1166        // Skip and validate the domain name in the record
1167        // skip_name already includes hostname size validation
1168        offset = skip_name(packet, offset)?;
1169
1170        // Check if we have enough bytes for the fixed RR header fields (10 bytes)
1171        if packet_len < offset || packet_len - offset < 10 {
1172            return Err(DnsError::PacketTooShort { offset });
1173        }
1174
1175        // Safely read RDLEN
1176        if offset + 8 >= packet_len {
1177            return Err(DnsError::PacketTooShort { offset });
1178        }
1179        let rdlen = BigEndian::read_u16(&packet[offset + 8..offset + 10]) as usize;
1180
1181        // Check for overflow when calculating rr_offset + 10 + rdlen
1182        let rdata_end = match offset.checked_add(10) {
1183            Some(offset_plus_10) => match offset_plus_10.checked_add(rdlen) {
1184                Some(end_offset) => end_offset,
1185                None => {
1186                    return Err(DnsError::InvalidRecord(
1187                        "Integer overflow calculating record data bounds".to_string(),
1188                    ));
1189                }
1190            },
1191            None => {
1192                return Err(DnsError::InvalidRecord(
1193                    "Integer overflow calculating record offset".to_string(),
1194                ));
1195            }
1196        };
1197
1198        if packet_len < rdata_end {
1199            return Err(DnsError::InvalidRecord(
1200                "Record length would exceed packet length".to_string(),
1201            ));
1202        }
1203
1204        callback(offset)?;
1205
1206        // For certain record types that contain domain names in their RDATA,
1207        // we should validate those domain names too
1208        let rr_type = BigEndian::read_u16(&packet[offset..offset + 2]);
1209        match rr_type {
1210            DNS_TYPE_NS | DNS_TYPE_CNAME | DNS_TYPE_PTR | DNS_TYPE_MX | DNS_TYPE_SRV
1211                // These record types contain domain names in their RDATA
1212                // Check that the RDATA size is reasonable
1213                if rdlen > DNS_MAX_HOSTNAME_SIZE => {
1214                    debug!("Large RDATA for domain name record: {rdlen} bytes (type: {rr_type})");
1215                }
1216            _ => {}
1217        }
1218
1219        // Safely advance the offset
1220        offset = match offset.checked_add(10) {
1221            Some(o) => match o.checked_add(rdlen) {
1222                Some(final_offset) => final_offset,
1223                None => {
1224                    return Err(DnsError::InvalidRecord(
1225                        "Integer overflow calculating next record offset".to_string(),
1226                    ));
1227                }
1228            },
1229            None => {
1230                return Err(DnsError::InvalidRecord(
1231                    "Integer overflow calculating next record offset".to_string(),
1232                ));
1233            }
1234        };
1235    }
1236
1237    Ok(offset)
1238}
1239
1240/// Traverses resource records in a mutable DNS packet and calls a callback for each record
1241///
1242/// This function iterates through a specified number of resource records in a mutable DNS packet,
1243/// calling the provided callback function for each record. It handles domain name compression
1244/// and validates record boundaries. Unlike `traverse_rrs`, this function allows modification
1245/// of the packet data.
1246///
1247/// # Arguments
1248///
1249/// * `packet` - The mutable DNS packet data
1250/// * `offset` - Starting offset in the packet where the resource records begin
1251/// * `rrcount` - Number of resource records to traverse
1252/// * `callback` - Function to call for each resource record, receiving the packet and offset of the record
1253///
1254/// # Returns
1255///
1256/// The final offset after traversing all records, or an error if packet validation fails
1257fn traverse_rrs_mut<F>(
1258    packet: &mut [u8],
1259    mut offset: usize,
1260    rrcount: usize,
1261    mut callback: F,
1262) -> DnsResult<usize>
1263where
1264    F: FnMut(&mut [u8], usize) -> DnsResult<()>,
1265{
1266    let packet_len = packet.len();
1267
1268    for _ in 0..rrcount {
1269        // Skip and validate the domain name in the record
1270        // skip_name already includes hostname size validation
1271        offset = skip_name(packet, offset)?;
1272
1273        // Check if we have enough bytes for the fixed RR header fields (10 bytes)
1274        if packet_len < offset || packet_len - offset < 10 {
1275            return Err(DnsError::PacketTooShort { offset });
1276        }
1277
1278        // Safely read RDLEN
1279        if offset + 8 >= packet_len {
1280            return Err(DnsError::PacketTooShort { offset });
1281        }
1282        let rdlen = BigEndian::read_u16(&packet[offset + 8..offset + 10]) as usize;
1283
1284        // Check for overflow when calculating rr_offset + 10 + rdlen
1285        let rdata_end = match offset.checked_add(10) {
1286            Some(offset_plus_10) => match offset_plus_10.checked_add(rdlen) {
1287                Some(end_offset) => end_offset,
1288                None => {
1289                    return Err(DnsError::InvalidRecord(
1290                        "Integer overflow calculating record data bounds".to_string(),
1291                    ));
1292                }
1293            },
1294            None => {
1295                return Err(DnsError::InvalidRecord(
1296                    "Integer overflow calculating record offset".to_string(),
1297                ));
1298            }
1299        };
1300
1301        if packet_len < rdata_end {
1302            return Err(DnsError::InvalidRecord(
1303                "Record length would exceed packet length".to_string(),
1304            ));
1305        }
1306
1307        callback(packet, offset)?;
1308
1309        // For certain record types that contain domain names in their RDATA,
1310        // we should validate those domain names too
1311        let rr_type = BigEndian::read_u16(&packet[offset..offset + 2]);
1312        match rr_type {
1313            DNS_TYPE_NS | DNS_TYPE_CNAME | DNS_TYPE_PTR | DNS_TYPE_MX | DNS_TYPE_SRV
1314                // These record types contain domain names in their RDATA
1315                // Check that the RDATA size is reasonable
1316                if rdlen > DNS_MAX_HOSTNAME_SIZE => {
1317                    debug!("Large RDATA for domain name record: {rdlen} bytes (type: {rr_type})");
1318                }
1319            _ => {}
1320        }
1321
1322        // Safely advance the offset
1323        offset = match offset.checked_add(10) {
1324            Some(o) => match o.checked_add(rdlen) {
1325                Some(final_offset) => final_offset,
1326                None => {
1327                    return Err(DnsError::InvalidRecord(
1328                        "Integer overflow calculating next record offset".to_string(),
1329                    ));
1330                }
1331            },
1332            None => {
1333                return Err(DnsError::InvalidRecord(
1334                    "Integer overflow calculating next record offset".to_string(),
1335                ));
1336            }
1337        };
1338    }
1339
1340    Ok(offset)
1341}
1342
1343/// Adds an EDNS section to a DNS packet
1344pub fn add_edns_section(packet: &mut Vec<u8>, max_payload_size: u16) -> DnsResult<()> {
1345    if packet.len() < DNS_HEADER_SIZE {
1346        return Err(DnsError::PacketTooShort { offset: 0 });
1347    }
1348    if packet.len() > DNS_MAX_PACKET_SIZE {
1349        return Err(DnsError::PacketTooLarge {
1350            size: packet.len(),
1351            max_size: DNS_MAX_PACKET_SIZE,
1352        });
1353    }
1354    if extract_edns_version(packet)?.is_some() {
1355        return Err(DnsError::InvalidEdns(
1356            "Packet already contains an OPT record".to_string(),
1357        ));
1358    }
1359
1360    // Create the OPT record
1361    let opt_rr: [u8; 11] = [
1362        0,                             // Root domain name
1363        (DNS_TYPE_OPT >> 8) as u8,     // TYPE = OPT (41), high byte
1364        DNS_TYPE_OPT as u8,            // TYPE = OPT (41), low byte
1365        (max_payload_size >> 8) as u8, // UDP payload size, high byte
1366        max_payload_size as u8,        // UDP payload size, low byte
1367        0,                             // Higher bits of extended RCODE and flags
1368        0,                             // EDNS version and flags
1369        0,                             // EDNS version and flags
1370        0,                             // Reserved
1371        0,                             // RDLEN, high byte
1372        0,                             // RDLEN, low byte
1373    ];
1374
1375    // Make sure the packet won't be too large
1376    if DNS_MAX_PACKET_SIZE - packet.len() < opt_rr.len() {
1377        return Err(DnsError::PacketTooLarge {
1378            size: packet.len(),
1379            max_size: DNS_MAX_PACKET_SIZE,
1380        });
1381    }
1382
1383    // Increment the Additional Records count
1384    let arcount_offset = 10; // Offset of ARCOUNT in DNS header
1385    let mut arcount = BigEndian::read_u16(&packet[arcount_offset..arcount_offset + 2]);
1386    if arcount == 0xffff {
1387        return Err(DnsError::InvalidPacket(
1388            "Too many additional records".to_string(),
1389        ));
1390    }
1391    arcount += 1;
1392    BigEndian::write_u16(&mut packet[arcount_offset..arcount_offset + 2], arcount);
1393
1394    // Add the OPT record
1395    packet.extend_from_slice(&opt_rr);
1396
1397    Ok(())
1398}
1399
1400/// Adds an EDNS-client-subnet option to an existing OPT record in a DNS packet
1401///
1402/// This function adds an EDNS-client-subnet option to an existing OPT record in a DNS packet.
1403/// If no OPT record exists, it will first add one with the specified maximum payload size.
1404///
1405/// # Arguments
1406///
1407/// * `packet` - The DNS packet to add the EDNS-client-subnet option to
1408/// * `client_ip` - The client IP address to include in the subnet option
1409/// * `prefix_v4` - The prefix length for IPv4 addresses (1-32)
1410/// * `prefix_v6` - The prefix length for IPv6 addresses (1-128)
1411/// * `max_payload_size` - The maximum payload size to use if adding a new OPT record
1412///
1413/// # Returns
1414///
1415/// * `Ok(())` - If the option was added successfully
1416/// * `Err(e)` - If there was an error adding the option
1417///
1418/// # RFC 7871 - Client Subnet in DNS Queries
1419///
1420/// This implements the EDNS-client-subnet option as defined in RFC 7871.
1421/// The option includes:
1422/// - FAMILY: Address family (1 for IPv4, 2 for IPv6)
1423/// - SOURCE PREFIX-LENGTH: Length of the prefix of the address to include
1424/// - SCOPE PREFIX-LENGTH: Set to 0 in queries, indicates how much of the address was used in responses
1425/// - ADDRESS: The truncated IP address (only including the prefix)
1426pub fn add_edns_client_subnet(
1427    packet: &mut Vec<u8>,
1428    client_ip: &str,
1429    prefix_v4: u8,
1430    prefix_v6: u8,
1431    max_payload_size: u16,
1432) -> DnsResult<()> {
1433    // Validate the client IP address
1434    let ip_addr = match client_ip.parse::<std::net::IpAddr>() {
1435        Ok(addr) => addr,
1436        Err(_) => {
1437            debug!("Invalid client IP address for EDNS-client-subnet: {client_ip}");
1438            return Ok(()); // Silently ignore invalid IP addresses
1439        }
1440    };
1441
1442    // Determine if we need to add an OPT record first
1443    let mut has_opt_record = false;
1444    let mut opt_record_offset = 0;
1445    let mut opt_record_rdlen_offset = 0;
1446
1447    // Skip the question section
1448    let mut offset = skip_name(packet, DNS_OFFSET_QUESTION)?;
1449    offset += 4; // Skip QTYPE and QCLASS
1450
1451    // Skip answer and authority sections
1452    let (ancount, nscount, arcount) = (ancount(packet), nscount(packet), arcount(packet));
1453    offset = traverse_rrs(packet, offset, ancount as usize + nscount as usize, |_| {
1454        Ok(())
1455    })?;
1456
1457    // Check additional records for OPT
1458    traverse_rrs(packet, offset, arcount as usize, |rr_offset| {
1459        let qtype = BigEndian::read_u16(&packet[rr_offset..]);
1460        if qtype == DNS_TYPE_OPT {
1461            has_opt_record = true;
1462            opt_record_offset = rr_offset;
1463            opt_record_rdlen_offset = rr_offset + 8; // RDLEN is at offset 8 in the OPT record
1464        }
1465        Ok(())
1466    })?;
1467
1468    // If no OPT record exists, add one
1469    if !has_opt_record {
1470        add_edns_section(packet, max_payload_size)?;
1471
1472        // Now find the OPT record we just added
1473        offset = skip_name(packet, DNS_OFFSET_QUESTION)?;
1474        offset += 4; // Skip QTYPE and QCLASS
1475
1476        // Skip answer and authority sections
1477        offset = traverse_rrs(packet, offset, ancount as usize + nscount as usize, |_| {
1478            Ok(())
1479        })?;
1480
1481        // Find the OPT record in the additional section
1482        traverse_rrs(packet, offset, arcount as usize + 1, |rr_offset| {
1483            let qtype = BigEndian::read_u16(&packet[rr_offset..]);
1484            if qtype == DNS_TYPE_OPT {
1485                has_opt_record = true;
1486                opt_record_offset = rr_offset;
1487                opt_record_rdlen_offset = rr_offset + 8; // RDLEN is at offset 8 in the OPT record
1488            }
1489            Ok(())
1490        })?;
1491    }
1492
1493    // If we still don't have an OPT record, something went wrong
1494    if !has_opt_record {
1495        return Err(DnsError::InvalidEdns(
1496            "Failed to add OPT record".to_string(),
1497        ));
1498    }
1499
1500    remove_edns_option(packet, EDNS_OPTION_CLIENT_SUBNET)?;
1501    let rdlen_offset = opt_record_rdlen_offset;
1502    let rdlen = BigEndian::read_u16(&packet[rdlen_offset..rdlen_offset + 2]) as usize;
1503    let rdata_offset = rdlen_offset + 2;
1504
1505    // Create the EDNS-client-subnet option
1506    let mut ecs_option = Vec::new();
1507
1508    // Determine family, source prefix length, and address bytes based on IP type
1509    let (family, source_prefix_length, address_bytes) = match ip_addr {
1510        std::net::IpAddr::V4(ipv4) => {
1511            if prefix_v4 > 32 {
1512                return Err(DnsError::InvalidEdns(format!(
1513                    "Invalid ECS prefix length {prefix_v4} for IPv4"
1514                )));
1515            }
1516            let bytes = ipv4.octets();
1517            (1u16, prefix_v4, bytes.to_vec())
1518        }
1519        std::net::IpAddr::V6(ipv6) => {
1520            if prefix_v6 > 128 {
1521                return Err(DnsError::InvalidEdns(format!(
1522                    "Invalid ECS prefix length {prefix_v6} for IPv6"
1523                )));
1524            }
1525            let bytes = ipv6.octets();
1526            (2u16, prefix_v6, bytes.to_vec())
1527        }
1528    };
1529
1530    // Calculate how many bytes we need to represent the prefix
1531    let address_byte_count = (source_prefix_length as usize).div_ceil(8);
1532
1533    // Truncate the address bytes to the specified prefix length
1534    let mut truncated_address = address_bytes[..address_byte_count].to_vec();
1535
1536    // If we're not using all bits in the last byte, mask it
1537    if address_byte_count > 0 && source_prefix_length % 8 != 0 {
1538        let last_byte_index = address_byte_count - 1;
1539        let mask = 0xffu8 << (8 - (source_prefix_length % 8));
1540        truncated_address[last_byte_index] &= mask;
1541    }
1542
1543    // Build the option
1544    // OPTION-CODE (CLIENT-SUBNET)
1545    ecs_option.push((EDNS_OPTION_CLIENT_SUBNET >> 8) as u8);
1546    ecs_option.push(EDNS_OPTION_CLIENT_SUBNET as u8);
1547
1548    // OPTION-LENGTH
1549    let option_length = 4 + truncated_address.len(); // 2 for family, 1 for source prefix length, 1 for scope prefix length, plus address bytes
1550    ecs_option.push((option_length >> 8) as u8);
1551    ecs_option.push(option_length as u8);
1552
1553    // FAMILY
1554    ecs_option.push((family >> 8) as u8);
1555    ecs_option.push(family as u8);
1556
1557    // SOURCE PREFIX-LENGTH
1558    ecs_option.push(source_prefix_length);
1559
1560    // SCOPE PREFIX-LENGTH (always 0 in queries)
1561    ecs_option.push(0);
1562
1563    // ADDRESS
1564    ecs_option.extend_from_slice(&truncated_address);
1565
1566    // Make sure the packet won't be too large
1567    if DNS_MAX_PACKET_SIZE.saturating_sub(packet.len()) < ecs_option.len() {
1568        return Err(DnsError::PacketTooLarge {
1569            size: packet.len(),
1570            max_size: DNS_MAX_PACKET_SIZE,
1571        });
1572    }
1573
1574    // Update the RDLEN in the OPT record
1575    let new_rdlen = rdlen + ecs_option.len();
1576    BigEndian::write_u16(
1577        &mut packet[rdlen_offset..rdlen_offset + 2],
1578        new_rdlen as u16,
1579    );
1580
1581    // Add the option to the end of the OPT record
1582    packet.splice(rdata_offset + rdlen..rdata_offset + rdlen, ecs_option);
1583
1584    Ok(())
1585}
1586
1587/// Sets the EDNS maximum payload size in a DNS packet
1588pub fn set_edns_max_payload_size(packet: &mut Vec<u8>, max_payload_size: u16) -> DnsResult<()> {
1589    let packet_len = packet.len();
1590    if packet_len <= DNS_OFFSET_QUESTION {
1591        return Err(DnsError::PacketTooShort { offset: 0 });
1592    }
1593    if packet_len > DNS_MAX_PACKET_SIZE {
1594        return Err(DnsError::PacketTooLarge {
1595            size: packet_len,
1596            max_size: DNS_MAX_PACKET_SIZE,
1597        });
1598    }
1599    if qdcount(packet) == 0 {
1600        return Err(DnsError::InvalidPacket("No question".to_string()));
1601    }
1602
1603    // Skip the question section
1604    let mut offset = skip_name(packet, DNS_OFFSET_QUESTION)?;
1605    if packet_len - offset < 4 {
1606        return Err(DnsError::PacketTooShort { offset: 0 });
1607    }
1608    offset += 4; // Skip QTYPE and QCLASS
1609
1610    // Skip answer and authority sections
1611    let (ancount, nscount, arcount) = (ancount(packet), nscount(packet), arcount(packet));
1612    offset = traverse_rrs(packet, offset, ancount as usize + nscount as usize, |_| {
1613        Ok(())
1614    })?;
1615
1616    // Check additional records for OPT
1617    let mut edns_payload_set = false;
1618
1619    traverse_rrs_mut(packet, offset, arcount as usize, |packet, offset| {
1620        let qtype = BigEndian::read_u16(&packet[offset..]);
1621        if qtype == DNS_TYPE_OPT {
1622            if edns_payload_set {
1623                return Err(DnsError::InvalidEdns("Duplicate OPT RR found".to_string()));
1624            }
1625            BigEndian::write_u16(&mut packet[offset + 2..], max_payload_size);
1626            edns_payload_set = true;
1627        }
1628        Ok(())
1629    })?;
1630
1631    // If no EDNS record was found, add one
1632    if !edns_payload_set {
1633        add_edns_section(packet, max_payload_size)?;
1634    }
1635
1636    Ok(())
1637}
1638
1639/// Extracts the EDNS version from a DNS packet
1640///
1641/// The EDNS version is stored in byte 3 of the TTL field in OPT records.
1642/// Returns None if no OPT record is found, or Some(version) if found.
1643pub fn extract_edns_version(packet: &[u8]) -> DnsResult<Option<u8>> {
1644    let packet_len = packet.len();
1645    if packet_len <= DNS_OFFSET_QUESTION {
1646        return Ok(None);
1647    }
1648
1649    // Skip the question section
1650    let mut offset = skip_name(packet, DNS_OFFSET_QUESTION)?;
1651    if packet_len - offset < 4 {
1652        return Ok(None);
1653    }
1654    offset += 4; // Skip QTYPE and QCLASS
1655
1656    // Skip answer and authority sections
1657    let (ancount, nscount, arcount) = (ancount(packet), nscount(packet), arcount(packet));
1658    offset = traverse_rrs(packet, offset, ancount as usize + nscount as usize, |_| {
1659        Ok(())
1660    })?;
1661
1662    // Check additional records for OPT
1663    let mut edns_version = None;
1664
1665    traverse_rrs(packet, offset, arcount as usize, |offset| {
1666        // Check we have at least 8 bytes for TYPE, CLASS, TTL
1667        if offset.checked_add(8).is_none_or(|sum| sum > packet_len) {
1668            return Ok(()); // Skip malformed record
1669        }
1670
1671        let rr_type = BigEndian::read_u16(&packet[offset..offset + 2]);
1672        if rr_type == DNS_TYPE_OPT {
1673            // The TTL field in OPT records contains:
1674            // Byte 0: Extended RCODE
1675            // Byte 1: EDNS Version
1676            // Bytes 2-3: Flags
1677            // The TTL is at offset + 4 (after TYPE and CLASS)
1678            let ttl_bytes = &packet[offset + 4..offset + 8];
1679            edns_version = Some(ttl_bytes[1]); // Byte 1 is the EDNS version
1680        }
1681        Ok(())
1682    })?;
1683
1684    Ok(edns_version)
1685}
1686
1687/// Validates that a DNS packet is a valid response
1688pub fn validate_dns_response(packet: &[u8]) -> DnsResult<()> {
1689    // First, validate that it's a valid DNS packet
1690    validate_dns_packet(packet)?;
1691
1692    // Check that it's a response (QR bit set)
1693    if !is_response(packet) {
1694        return Err(DnsError::InvalidPacket("Not a response".to_string()));
1695    }
1696
1697    // Check that we have at least one answer or an error code
1698    let qdcount = qdcount(packet);
1699    let rcode = rcode(packet);
1700
1701    if qdcount != 1 && rcode == 0 {
1702        return Err(DnsError::InvalidPacket(
1703            "No question in successful response".to_string(),
1704        ));
1705    }
1706
1707    Ok(())
1708}
1709
1710/// Sets the transaction ID in a DNS packet
1711pub fn set_tid(packet: &mut [u8], tid: u16) -> DnsResult<()> {
1712    if packet.len() < 2 {
1713        return Err(DnsError::PacketTooShort { offset: 0 });
1714    }
1715
1716    // DNS transaction ID is the first 2 bytes of the packet
1717    packet[0] = (tid >> 8) as u8;
1718    packet[1] = tid as u8;
1719
1720    Ok(())
1721}
1722
1723/// Returns the flags field from the DNS packet
1724///
1725/// The flags field contains various DNS header flags including:
1726/// - QR (Query/Response) bit
1727/// - Opcode (operation code)
1728/// - AA (Authoritative Answer) bit
1729/// - TC (Truncation) bit
1730/// - RD (Recursion Desired) bit
1731/// - RA (Recursion Available) bit
1732/// - Z (Reserved for future use)
1733/// - AD (Authentic Data) bit
1734/// - CD (Checking Disabled) bit
1735/// - RCODE (Response code)
1736///
1737/// # Arguments
1738///
1739/// * `packet` - The DNS packet data
1740///
1741/// # Returns
1742///
1743/// The 16-bit flags field value, or 0 for malformed packets
1744#[inline]
1745pub fn flags(packet: &[u8]) -> u16 {
1746    if packet.len() < 4 {
1747        return 0; // Return 0 for malformed packets
1748    }
1749    BigEndian::read_u16(&packet[2..4])
1750}
1751
1752/// Sets the flags field in a DNS packet
1753pub fn set_flags(packet: &mut [u8], flags: u16) -> DnsResult<()> {
1754    if packet.len() < 4 {
1755        return Err(DnsError::PacketTooShort { offset: 0 });
1756    }
1757
1758    // DNS flags are bytes 2-3 of the packet
1759    packet[2] = (flags >> 8) as u8;
1760    packet[3] = flags as u8;
1761
1762    Ok(())
1763}
1764
1765/// Sets the QR bit in a DNS packet (0 for query, 1 for response)
1766pub fn set_qr(packet: &mut [u8], is_response: bool) -> DnsResult<()> {
1767    if packet.len() < 4 {
1768        return Err(DnsError::PacketTooShort { offset: 0 });
1769    }
1770
1771    let mut flags_val = flags(packet);
1772    if is_response {
1773        flags_val |= DNS_FLAGS_QR; // Set QR bit
1774    } else {
1775        flags_val &= !DNS_FLAGS_QR; // Clear QR bit
1776    }
1777    set_flags(packet, flags_val)
1778}
1779
1780/// Sets the TC bit in a DNS packet (1 for truncated)
1781pub fn set_tc(packet: &mut [u8], is_truncated: bool) -> DnsResult<()> {
1782    if packet.len() < 4 {
1783        return Err(DnsError::PacketTooShort { offset: 0 });
1784    }
1785
1786    let mut flags_val = flags(packet);
1787    if is_truncated {
1788        flags_val |= DNS_FLAGS_TC; // Set TC bit
1789    } else {
1790        flags_val &= !DNS_FLAGS_TC; // Clear TC bit
1791    }
1792    set_flags(packet, flags_val)
1793}
1794
1795/// Sets the AA (Authoritative Answer) bit in a DNS packet
1796pub fn set_aa(packet: &mut [u8], is_authoritative: bool) -> DnsResult<()> {
1797    if packet.len() < 4 {
1798        return Err(DnsError::PacketTooShort { offset: 0 });
1799    }
1800
1801    let mut flags_val = flags(packet);
1802    if is_authoritative {
1803        flags_val |= DNS_FLAGS_AA; // Set AA bit
1804    } else {
1805        flags_val &= !DNS_FLAGS_AA; // Clear AA bit
1806    }
1807    set_flags(packet, flags_val)
1808}
1809
1810/// Sets the RA (Recursion Available) bit in a DNS packet
1811pub fn set_ra(packet: &mut [u8], recursion_available: bool) -> DnsResult<()> {
1812    if packet.len() < 4 {
1813        return Err(DnsError::PacketTooShort { offset: 0 });
1814    }
1815
1816    let mut flags_val = flags(packet);
1817    if recursion_available {
1818        flags_val |= DNS_FLAGS_RA; // Set RA bit
1819    } else {
1820        flags_val &= !DNS_FLAGS_RA; // Clear RA bit
1821    }
1822    set_flags(packet, flags_val)
1823}
1824
1825/// Sets or clears the AD flag in a DNS packet.
1826pub fn set_ad(packet: &mut [u8], authenticated_data: bool) -> DnsResult<()> {
1827    if packet.len() < 4 {
1828        return Err(DnsError::PacketTooShort { offset: 0 });
1829    }
1830    let mut current_flags = flags(packet);
1831    if authenticated_data {
1832        current_flags |= DNS_FLAGS_AD;
1833    } else {
1834        current_flags &= !DNS_FLAGS_AD;
1835    }
1836    set_flags(packet, current_flags)
1837}
1838
1839/// Clears the RD, CD and AD flags of a query, since they don't change what an authoritative server answers.
1840pub fn clear_resolver_flags(query: &mut [u8]) -> DnsResult<()> {
1841    set_flags(
1842        query,
1843        flags(query) & !(DNS_FLAGS_RD | DNS_FLAGS_CD | DNS_FLAGS_AD),
1844    )
1845}
1846
1847/// Copies the RD and CD flags of a query into its response, as RFC 1035 and RFC 4035 require.
1848pub fn copy_rd_cd(response: &mut [u8], query: &[u8]) -> DnsResult<()> {
1849    if response.len() < 4 || query.len() < 4 {
1850        return Err(DnsError::PacketTooShort { offset: 0 });
1851    }
1852    let copied = DNS_FLAGS_RD | DNS_FLAGS_CD;
1853    set_flags(
1854        response,
1855        (flags(response) & !copied) | (flags(query) & copied),
1856    )
1857}
1858
1859/// Sets the answer count in a DNS packet
1860pub fn set_ancount(packet: &mut [u8], count: u16) -> DnsResult<()> {
1861    if packet.len() < 8 {
1862        return Err(DnsError::PacketTooShort { offset: 0 });
1863    }
1864
1865    BigEndian::write_u16(&mut packet[6..8], count);
1866    Ok(())
1867}
1868
1869/// Sets the authority count in a DNS packet
1870pub fn set_nscount(packet: &mut [u8], count: u16) -> DnsResult<()> {
1871    if packet.len() < 10 {
1872        return Err(DnsError::PacketTooShort { offset: 0 });
1873    }
1874
1875    BigEndian::write_u16(&mut packet[8..10], count);
1876    Ok(())
1877}
1878
1879/// Sets the additional count in a DNS packet
1880pub fn set_arcount(packet: &mut [u8], count: u16) -> DnsResult<()> {
1881    if packet.len() < DNS_PACKET_LEN_MIN {
1882        return Err(DnsError::PacketTooShort { offset: 0 });
1883    }
1884
1885    BigEndian::write_u16(&mut packet[10..DNS_PACKET_LEN_MIN], count);
1886    Ok(())
1887}
1888
1889/// Sets the RCODE in a DNS packet
1890pub fn set_rcode(packet: &mut [u8], rcode: u8) -> DnsResult<()> {
1891    if packet.len() < DNS_PACKET_LEN_MIN {
1892        return Err(DnsError::PacketTooShort { offset: 0 });
1893    }
1894
1895    // For standard RCODEs (0-15), set in the header
1896    if rcode <= 0x0F {
1897        // Clear the lower 4 bits and set the new RCODE
1898        packet[3] = (packet[3] & 0xF0) | (rcode & 0x0F);
1899        Ok(())
1900    } else {
1901        // For extended RCODEs (16-255), we need to handle them differently
1902        // Set lower 4 bits to 0 in header
1903        packet[3] &= 0xF0;
1904
1905        // Extended RCODEs require an OPT record to hold the upper bits
1906        // This should be handled by the caller when creating extended RCODE responses
1907        Ok(())
1908    }
1909}
1910
1911/// Extracts the EDNS0 maximum datagram size from a DNS packet
1912///
1913/// This function searches for an OPT record in the additional section of a DNS packet
1914/// and returns the maximum payload size if found.
1915///
1916/// # Arguments
1917///
1918/// * `packet` - The DNS packet to extract the EDNS0 maximum datagram size from
1919///
1920/// # Returns
1921///
1922/// * `Some(max_size)` - The maximum payload size if an OPT record is found
1923/// * `None` - If no OPT record is found or if the packet doesn't have additional records
1924pub fn extract_edns0_max_size(packet: &[u8]) -> DnsResult<Option<u16>> {
1925    let packet_len = packet.len();
1926    if packet_len < DNS_PACKET_LEN_MIN {
1927        return Err(DnsError::PacketTooShort { offset: 0 });
1928    }
1929    if packet_len > DNS_MAX_PACKET_SIZE {
1930        return Err(DnsError::PacketTooLarge {
1931            size: packet_len,
1932            max_size: DNS_MAX_PACKET_SIZE,
1933        });
1934    }
1935
1936    // Check if there are any additional records
1937    let arcount_val = arcount(packet);
1938    if arcount_val == 0 {
1939        // No additional records, so no EDNS0
1940        return Ok(None);
1941    }
1942
1943    // Check if there's at least one question
1944    let qdcount_val = qdcount(packet);
1945    if qdcount_val == 0 {
1946        return Err(DnsError::InvalidPacket("No question".to_string()));
1947    }
1948
1949    // Try to skip the question section
1950    let mut offset = DNS_HEADER_SIZE;
1951
1952    // Skip all questions
1953    for _ in 0..qdcount_val {
1954        match skip_name(packet, offset) {
1955            Ok(new_offset) => {
1956                offset = new_offset;
1957                // Skip QTYPE and QCLASS
1958                if packet_len - offset < 4 {
1959                    return Err(DnsError::PacketTooShort { offset: 0 });
1960                }
1961                offset += 4;
1962            }
1963            Err(_) => {
1964                // If we can't skip the question, assume there's no EDNS0
1965                return Ok(None);
1966            }
1967        }
1968    }
1969
1970    // Skip answer and authority sections
1971    let (ancount_val, nscount_val) = (ancount(packet), nscount(packet));
1972
1973    // Try to skip answer and authority sections
1974    match traverse_rrs(
1975        packet,
1976        offset,
1977        ancount_val as usize + nscount_val as usize,
1978        |_| Ok(()),
1979    ) {
1980        Ok(new_offset) => {
1981            offset = new_offset;
1982        }
1983        Err(_) => {
1984            // If we can't traverse the records, assume there's no EDNS0
1985            return Ok(None);
1986        }
1987    }
1988
1989    // Check additional records for OPT
1990    let mut max_size: Option<u16> = None;
1991
1992    // Try to traverse additional records
1993    match traverse_rrs(packet, offset, arcount_val as usize, |offset| {
1994        if packet_len - offset < 2 {
1995            return Ok(());
1996        }
1997
1998        let qtype = BigEndian::read_u16(&packet[offset..]);
1999        if qtype == DNS_TYPE_OPT {
2000            // OPT record found, extract the maximum payload size
2001            // The maximum payload size is in the CLASS field (bytes 2-3 of the OPT record)
2002            if packet_len - offset < 4 {
2003                return Ok(());
2004            }
2005
2006            let size = BigEndian::read_u16(&packet[offset + 2..]);
2007            if max_size.is_none() {
2008                max_size = Some(size);
2009            }
2010        }
2011        Ok(())
2012    }) {
2013        Ok(_) => {}
2014        Err(_) => {
2015            // If we can't traverse the additional records, assume there's no EDNS0
2016            return Ok(None);
2017        }
2018    }
2019
2020    Ok(max_size)
2021}
2022
2023/// Creates or truncates a DNS message to fit within a maximum size
2024///
2025/// This function can:
2026/// 1. Convert a DNS query into a truncated DNS response
2027/// 2. Truncate a DNS response to fit within a maximum size
2028///
2029/// In both cases, it preserves the header and question section, but removes all answer,
2030/// authority, and additional records. It sets the TC bit to 1 (truncated) to indicate
2031/// that the response is truncated.
2032///
2033/// # Arguments
2034///
2035/// * `packet` - The DNS packet (query or response) to process
2036/// * `max_size` - Optional maximum size for the result. If None, the function will always truncate.
2037///   If Some(size), it will only truncate if the packet exceeds the size.
2038/// * `force_response` - If true, ensures the result is a response (sets QR bit to 1)
2039///
2040/// # Returns
2041///
2042/// A new Vec<u8> containing the truncated DNS message
2043pub fn truncate_dns_packet(
2044    packet: &[u8],
2045    max_size: Option<usize>,
2046    force_response: bool,
2047) -> DnsResult<Vec<u8>> {
2048    // First, check if the packet is valid
2049    if packet.len() < DNS_PACKET_LEN_MIN {
2050        return Err(DnsError::PacketTooShort { offset: 0 });
2051    }
2052
2053    // Check if the packet is already small enough (if max_size is provided)
2054    if let Some(size) = max_size
2055        && packet.len() <= size
2056    {
2057        return Ok(packet.to_vec());
2058    }
2059
2060    // Create a new packet with the same header and question
2061    let mut truncated_data = packet.to_vec();
2062
2063    // Skip the question section to find where to truncate
2064    let mut offset = DNS_HEADER_SIZE;
2065    let qdcount = qdcount(&truncated_data);
2066
2067    if qdcount == 0 {
2068        return Err(DnsError::InvalidPacket("No question in packet".to_string()));
2069    }
2070
2071    for _ in 0..qdcount {
2072        offset = skip_name(&truncated_data, offset)?;
2073        if truncated_data.len() - offset < 4 {
2074            return Err(DnsError::PacketTooShort { offset: 0 });
2075        }
2076        offset += 4; // Skip QTYPE and QCLASS
2077    }
2078
2079    // Truncate the packet after the question section
2080    truncated_data.truncate(offset);
2081
2082    // If force_response is true, set the QR bit to 1 (response)
2083    if force_response && !is_response(&truncated_data) {
2084        set_qr(&mut truncated_data, true)?;
2085    }
2086
2087    // Set the TC bit to 1 (truncated)
2088    set_tc(&mut truncated_data, true)?;
2089
2090    // Set answer, authority, and additional counts to 0
2091    set_ancount(&mut truncated_data, 0)?;
2092    set_nscount(&mut truncated_data, 0)?;
2093    set_arcount(&mut truncated_data, 0)?;
2094
2095    Ok(truncated_data)
2096}
2097
2098/// Creates a truncated DNS response from a DNS query
2099///
2100/// This function takes a DNS query and converts it into a truncated DNS response
2101/// by preserving the header and question section, but removing all answer, authority,
2102/// and additional records. It sets the QR bit to 1 (response) and the TC bit to 1 (truncated).
2103///
2104/// # Arguments
2105///
2106/// * `query` - The DNS query to convert to a truncated response
2107///
2108/// # Returns
2109///
2110/// A new Vec<u8> containing a truncated DNS response
2111#[allow(dead_code)]
2112pub fn create_truncated_response(query: &[u8]) -> DnsResult<Vec<u8>> {
2113    // Check that this is a query, not a response
2114    if is_response(query) {
2115        return Err(DnsError::InvalidPacket(
2116            "Expected a query, got a response".to_string(),
2117        ));
2118    }
2119
2120    // Use the generic truncate_dns_packet function with force_response=true
2121    truncate_dns_packet(query, None, true)
2122}
2123
2124/// Truncates a DNS response to fit within the maximum UDP packet size
2125///
2126/// This function takes a DNS response and truncates it to fit within the maximum UDP packet size
2127/// by preserving the header and question section, but removing answer, authority, and additional
2128/// records as needed. It sets the TC bit to 1 (truncated) to indicate that the response is truncated.
2129///
2130/// # Arguments
2131///
2132/// * `response` - The DNS response to truncate
2133/// * `max_size` - The maximum size of the truncated response
2134///
2135/// # Returns
2136///
2137/// A new Vec<u8> containing the truncated DNS response
2138#[allow(dead_code)]
2139pub fn truncate_response(response: &[u8], max_size: usize) -> DnsResult<Vec<u8>> {
2140    // Check that this is a response, not a query
2141    if !is_response(response) {
2142        return Err(DnsError::InvalidPacket(
2143            "Expected a response, got a query".to_string(),
2144        ));
2145    }
2146
2147    // Use the generic truncate_dns_packet function with force_response=false
2148    truncate_dns_packet(response, Some(max_size), false)
2149}
2150
2151/// Recovers a DNS query from a truncated DNS response
2152///
2153/// This function takes a truncated DNS response and converts it into a valid DNS query
2154/// by preserving the header and question section, but removing all answer, authority,
2155/// and additional records. It also sets the QR bit to 0 (query) and the TC bit to 0 (not truncated).
2156///
2157/// # Arguments
2158///
2159/// * `response` - The truncated DNS response
2160///
2161/// # Returns
2162///
2163/// A new Vec<u8> containing a valid DNS query
2164pub fn recover_question_from_response(response: &[u8]) -> DnsResult<Vec<u8>> {
2165    // First, check if the response is valid
2166    if response.len() < DNS_PACKET_LEN_MIN {
2167        return Err(DnsError::PacketTooShort { offset: 0 });
2168    }
2169
2170    // Create a new query with the same header and question
2171    let mut query_data = response.to_vec();
2172
2173    // Set the QR bit to 0 (query)
2174    set_qr(&mut query_data, false)?;
2175
2176    // Set the TC bit to 0 (not truncated)
2177    set_tc(&mut query_data, false)?;
2178
2179    // Keep only the header and question section
2180    let qdcount = qdcount(&query_data);
2181    if qdcount == 0 {
2182        return Err(DnsError::InvalidPacket(
2183            "No question in response".to_string(),
2184        ));
2185    }
2186
2187    let mut offset = DNS_HEADER_SIZE;
2188    for _ in 0..qdcount {
2189        offset = skip_name(&query_data, offset)?;
2190        if query_data.len() - offset < 4 {
2191            return Err(DnsError::PacketTooShort { offset: 0 });
2192        }
2193        offset = offset.checked_add(4).ok_or_else(|| {
2194            DnsError::InvalidPacket("Integer overflow advancing past QTYPE/QCLASS".to_string())
2195        })?;
2196    }
2197
2198    query_data.truncate(offset);
2199
2200    // Set answer, authority, and additional counts to 0
2201    set_ancount(&mut query_data, 0)?;
2202    set_nscount(&mut query_data, 0)?;
2203    set_arcount(&mut query_data, 0)?;
2204
2205    Ok(query_data)
2206}
2207
2208#[cfg(test)]
2209mod tests {
2210    use super::*;
2211
2212    // Helper function to create a simple DNS query packet
2213    fn create_test_query() -> Vec<u8> {
2214        // Create DNS Header (DNS_PACKET_LEN_MIN bytes)
2215        let mut packet = vec![
2216            // Transaction ID (2 bytes)
2217            0x12, 0x34, // Flags (2 bytes) - Standard query with RD bit set
2218            0x01, 0x00, // QDCOUNT (2 bytes) - 1 question
2219            0x00, 0x01, // ANCOUNT (2 bytes) - 0 answers
2220            0x00, 0x00, // NSCOUNT (2 bytes) - 0 authority records
2221            0x00, 0x00, // ARCOUNT (2 bytes) - 0 additional records
2222            0x00, 0x00,
2223        ];
2224
2225        // Question section - example.com A record
2226        // example
2227        packet.push(0x07); // Length of "example"
2228        for b in b"example" {
2229            packet.push(*b);
2230        }
2231        // com
2232        packet.push(0x03); // Length of "com"
2233        for b in b"com" {
2234            packet.push(*b);
2235        }
2236        // Root label
2237        packet.push(0x00);
2238
2239        // QTYPE (2 bytes) - A record
2240        packet.push(0x00);
2241        packet.push(0x01);
2242
2243        // QCLASS (2 bytes) - IN
2244        packet.push(0x00);
2245        packet.push(0x01);
2246
2247        packet
2248    }
2249
2250    // Helper function to create a DNS query with a specific opcode
2251    fn create_test_query_with_opcode(opcode: u8) -> Vec<u8> {
2252        let mut packet = create_test_query();
2253
2254        // Set the opcode in the flags field (bits 11-14 of the flags field)
2255        // Opcode is stored in bits 3-6 of byte 2
2256        packet[2] = (packet[2] & 0x87) | ((opcode & 0x0F) << 3);
2257
2258        packet
2259    }
2260
2261    // Helper function to create a DNS query with EDNS0
2262    fn create_test_query_with_edns0(max_size: u16) -> Vec<u8> {
2263        let mut packet = create_test_query();
2264
2265        // Add EDNS0 record
2266        // Increment ARCOUNT
2267        packet[11] = 0x01;
2268
2269        // Root domain name
2270        packet.push(0x00);
2271
2272        // TYPE = OPT (41)
2273        packet.push(0x00);
2274        packet.push(0x29);
2275
2276        // CLASS field is the maximum UDP payload size
2277        packet.push((max_size >> 8) as u8);
2278        packet.push(max_size as u8);
2279
2280        // TTL field (extended RCODE and flags)
2281        packet.push(0x00); // Extended RCODE
2282        packet.push(0x00); // Version
2283        packet.push(0x00); // High flags
2284        packet.push(0x00); // Low flags
2285
2286        // RDLEN
2287        packet.push(0x00);
2288        packet.push(0x00);
2289
2290        packet
2291    }
2292
2293    #[test]
2294    fn test_extract_edns0_max_size() {
2295        // Test with no EDNS0 record
2296        let query = create_test_query();
2297        println!("Query length: {}", query.len());
2298        let result = match extract_edns0_max_size(&query) {
2299            Ok(r) => r,
2300            Err(e) => {
2301                println!("Error extracting EDNS0 max size from query: {:?}", e);
2302                panic!("Failed to extract EDNS0 max size from query");
2303            }
2304        };
2305        assert_eq!(result, None);
2306
2307        // Test with EDNS0 record
2308        let query_with_edns0 = create_test_query_with_edns0(4096);
2309        println!("Query with EDNS0 length: {}", query_with_edns0.len());
2310
2311        // Validate that the helper returns the EDNS0 max size
2312        let edns0_size = extract_edns0_max_size(&query_with_edns0).unwrap();
2313        assert_eq!(edns0_size, Some(4096));
2314
2315        // Debug the packet
2316        println!("EDNS0 packet: {:?}", query_with_edns0);
2317
2318        // Direct test for the specific test packet
2319        // This is a simplified test that directly checks the OPT record
2320        // without going through the full parsing logic
2321        assert_eq!(query_with_edns0[11], 1); // ARCOUNT = 1
2322        assert_eq!(query_with_edns0[29], 0); // Root domain name
2323        assert_eq!(query_with_edns0[30], 0); // TYPE = OPT (41) high byte
2324        assert_eq!(query_with_edns0[31], 41); // TYPE = OPT (41) low byte
2325        assert_eq!(query_with_edns0[32], 16); // CLASS = 4096 high byte
2326        assert_eq!(query_with_edns0[33], 0); // CLASS = 4096 low byte
2327
2328        // The CLASS field in an OPT record is the maximum UDP payload size
2329        let max_size = (query_with_edns0[32] as u16) << 8 | query_with_edns0[33] as u16;
2330        assert_eq!(max_size, 4096);
2331    }
2332
2333    #[test]
2334    fn test_change_ttl_preserves_opt_metadata() {
2335        let mut response = create_test_query();
2336        set_qr(&mut response, true).unwrap();
2337        set_ancount(&mut response, 1).unwrap();
2338        response.extend_from_slice(&[
2339            0xc0, 0x0c, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x04, 192, 0, 2, 1,
2340        ]);
2341        add_edns_section(&mut response, 1232).unwrap();
2342
2343        let opt_start = response.len() - 11;
2344        response[opt_start + 5..opt_start + 9].copy_from_slice(&[0x12, 0x00, 0x80, 0x00]);
2345
2346        change_ttl(&mut response, 15).unwrap();
2347
2348        let answer_ttl_offset = 29 + 2 + 4;
2349        assert_eq!(
2350            &response[answer_ttl_offset..answer_ttl_offset + 4],
2351            &[0, 0, 0, 15]
2352        );
2353        assert_eq!(
2354            &response[opt_start + 5..opt_start + 9],
2355            &[0x12, 0x00, 0x80, 0x00]
2356        );
2357    }
2358
2359    #[test]
2360    fn test_decrement_ttl_preserves_individual_ttls_and_opt() {
2361        let mut response = create_test_query();
2362        set_qr(&mut response, true).unwrap();
2363        set_ancount(&mut response, 2).unwrap();
2364        response.extend_from_slice(&[
2365            0xc0, 0x0c, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x2c, 0x00, 0x04, 192, 0, 2, 1,
2366            0xc0, 0x0c, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x04, 192, 0, 2, 2,
2367        ]);
2368        add_edns_section(&mut response, 1232).unwrap();
2369        let opt_start = response.len() - 11;
2370        response[opt_start + 5..opt_start + 9].copy_from_slice(&[0x12, 0x00, 0x80, 0x00]);
2371
2372        decrement_ttl(&mut response, 10).unwrap();
2373
2374        assert_eq!(BigEndian::read_u32(&response[35..39]), 290);
2375        assert_eq!(BigEndian::read_u32(&response[51..55]), 50);
2376        assert_eq!(
2377            &response[opt_start + 5..opt_start + 9],
2378            &[0x12, 0x00, 0x80, 0x00]
2379        );
2380    }
2381
2382    #[test]
2383    fn test_question_matching() {
2384        let query = create_test_query();
2385        let mut response = query.clone();
2386        set_qr(&mut response, true).unwrap();
2387        assert!(questions_match(&query, &response).unwrap());
2388
2389        let qtype_offset = response.len() - 4;
2390        response[qtype_offset..qtype_offset + 2].copy_from_slice(&[0, 28]);
2391        assert!(!questions_match(&query, &response).unwrap());
2392
2393        response[13] = b'f';
2394        assert!(restore_qname_case(&mut response, &query).is_err());
2395
2396        // Without a question, there is nothing to fix
2397        response[5] = 0;
2398        restore_qname_case(&mut response, &query).unwrap();
2399        assert_eq!(response[13], b'f');
2400    }
2401
2402    #[test]
2403    fn test_dot_inside_label_is_rejected() {
2404        // The single label "example.com" instead of "example" and "com"
2405        let mut dotted = create_test_query();
2406        dotted[12] = 11;
2407        dotted[20] = b'.';
2408
2409        assert!(validate_dns_packet(&dotted).is_err());
2410    }
2411
2412    #[test]
2413    fn test_trailing_data_is_not_part_of_the_message() {
2414        let query = create_test_query();
2415        assert_eq!(validate_dns_packet(&query).unwrap(), query.len());
2416
2417        // An OPT record at the end that the header doesn't count
2418        let mut with_trailing_opt = query.clone();
2419        add_edns_section(&mut with_trailing_opt, 1232).unwrap();
2420        set_arcount(&mut with_trailing_opt, 0).unwrap();
2421        assert_eq!(
2422            validate_dns_packet(&with_trailing_opt).unwrap(),
2423            query.len()
2424        );
2425    }
2426
2427    #[test]
2428    fn test_invalid_opt_layout_is_rejected() {
2429        let mut duplicate = create_test_query();
2430        add_edns_section(&mut duplicate, 1232).unwrap();
2431        let opt = duplicate[duplicate.len() - 11..].to_vec();
2432        duplicate.extend_from_slice(&opt);
2433        set_arcount(&mut duplicate, 2).unwrap();
2434        assert!(validate_dns_packet(&duplicate).is_err());
2435
2436        let mut named = create_test_query();
2437        add_edns_section(&mut named, 1232).unwrap();
2438        let opt_start = named.len() - 11;
2439        named.splice(opt_start..=opt_start, [1, b'x', 0]);
2440        assert!(validate_dns_packet(&named).is_err());
2441    }
2442
2443    #[test]
2444    fn test_forward_compression_pointer_is_rejected() {
2445        let mut response = create_test_query();
2446        set_qr(&mut response, true).unwrap();
2447        set_ancount(&mut response, 1).unwrap();
2448        let answer_start = response.len();
2449        let pointer = answer_start + 2;
2450        response.extend_from_slice(&[
2451            0xc0 | ((pointer >> 8) as u8),
2452            pointer as u8,
2453            0x00,
2454            0x01,
2455            0x00,
2456            0x01,
2457            0x00,
2458            0x00,
2459            0x00,
2460            0x3c,
2461            0x00,
2462            0x04,
2463            192,
2464            0,
2465            2,
2466            1,
2467        ]);
2468
2469        assert!(validate_dns_packet(&response).is_err());
2470    }
2471
2472    #[test]
2473    fn test_wire_name_length_boundary() {
2474        fn query_with_labels(lengths: &[usize]) -> Vec<u8> {
2475            let mut query = vec![
2476                0x12, 0x34, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2477            ];
2478            for &length in lengths {
2479                query.push(length as u8);
2480                query.extend(std::iter::repeat_n(b'a', length));
2481            }
2482            query.extend_from_slice(&[0, 0, 1, 0, 1]);
2483            query
2484        }
2485
2486        assert!(validate_dns_packet(&query_with_labels(&[63, 63, 63, 61])).is_ok());
2487        assert!(validate_dns_packet(&query_with_labels(&[63, 63, 63, 62])).is_err());
2488    }
2489
2490    #[test]
2491    fn test_ecs_is_replaced_and_can_be_removed() {
2492        let mut query = create_test_query();
2493        add_edns_section(&mut query, 1232).unwrap();
2494        // A cookie, which must survive the ECS removal
2495        add_cookie(&mut query, b"CLIENT01");
2496        add_edns_client_subnet(&mut query, "192.0.2.129", 24, 56, 1232).unwrap();
2497        add_edns_client_subnet(&mut query, "198.51.100.9", 24, 56, 1232).unwrap();
2498
2499        let ecs = extract_edns_client_subnet(&query).unwrap().unwrap();
2500        assert_eq!(ecs.address, vec![198, 51, 100]);
2501
2502        remove_edns_option(&mut query, EDNS_OPTION_CLIENT_SUBNET).unwrap();
2503        assert!(extract_edns_client_subnet(&query).unwrap().is_none());
2504        assert_eq!(arcount(&query), 1);
2505
2506        let len = query.len();
2507        remove_edns_option(&mut query, EDNS_OPTION_COOKIE).unwrap();
2508        assert_eq!(query.len(), len - 12);
2509    }
2510
2511    #[test]
2512    fn test_truncate_dns_packet() {
2513        // Test truncating a query into a response
2514        let query = create_test_query();
2515        let truncated_response = truncate_dns_packet(&query, None, true).unwrap();
2516
2517        // Check that the response has the QR bit set
2518        assert!(is_response(&truncated_response));
2519
2520        // Check that the response has the TC bit set
2521        assert!(is_truncated(&truncated_response));
2522
2523        // Check that the response has the same transaction ID
2524        assert_eq!(tid(&truncated_response), 0x1234);
2525
2526        // Check that the response has the same question count
2527        assert_eq!(qdcount(&truncated_response), 1);
2528
2529        // Check that the response has no answer, authority, or additional records
2530        assert_eq!(ancount(&truncated_response), 0);
2531        assert_eq!(nscount(&truncated_response), 0);
2532        assert_eq!(arcount(&truncated_response), 0);
2533
2534        // Test truncating a response with max_size
2535        // First, create a response
2536        let mut response = query.to_vec();
2537        set_qr(&mut response, true).unwrap();
2538
2539        // Add some dummy data to make it larger
2540        response.extend_from_slice(&[0; 100]);
2541
2542        // Truncate the response
2543        let max_size = 50;
2544        let truncated_response = truncate_dns_packet(&response, Some(max_size), false).unwrap();
2545
2546        // Check that the response is smaller than max_size
2547        assert!(truncated_response.len() <= max_size);
2548
2549        // Check that the response has the QR bit set
2550        assert!(is_response(&truncated_response));
2551
2552        // Check that the response has the TC bit set
2553        assert!(is_truncated(&truncated_response));
2554    }
2555
2556    #[test]
2557    fn test_recover_question_from_response() {
2558        // Create a truncated response
2559        let query = create_test_query();
2560        let truncated_response = truncate_dns_packet(&query, None, true).unwrap();
2561
2562        // Recover the question from the truncated response
2563        let recovered_query = recover_question_from_response(&truncated_response).unwrap();
2564
2565        // Check that the recovered query is not a response
2566        assert!(!is_response(&recovered_query));
2567
2568        // Check that the recovered query is not truncated
2569        assert!(!is_truncated(&recovered_query));
2570
2571        // Check that the recovered query has the same transaction ID
2572        assert_eq!(tid(&recovered_query), 0x1234);
2573
2574        // Check that the recovered query has the same question count
2575        assert_eq!(qdcount(&recovered_query), 1);
2576
2577        // Check that the recovered query has no answer, authority, or additional records
2578        assert_eq!(ancount(&recovered_query), 0);
2579        assert_eq!(nscount(&recovered_query), 0);
2580        assert_eq!(arcount(&recovered_query), 0);
2581    }
2582
2583    #[test]
2584    fn test_recover_question_truncates_extra_data() {
2585        let query = create_test_query();
2586        let mut response = query.clone();
2587        set_qr(&mut response, true).unwrap();
2588        set_tc(&mut response, true).unwrap();
2589        response.extend_from_slice(&[0u8; 32]);
2590
2591        let recovered_query = recover_question_from_response(&response).unwrap();
2592        assert_eq!(recovered_query.len(), query.len());
2593    }
2594
2595    #[test]
2596    fn test_is_dnssec_requested_short_packet() {
2597        let result = is_dnssec_requested(&[0u8; 3]);
2598        assert!(matches!(result, Err(DnsError::PacketTooShort { .. })));
2599    }
2600
2601    #[test]
2602    fn test_opcode_validation() {
2603        // Test standard query (opcode 0)
2604        let query = create_test_query();
2605        assert_eq!(opcode(&query), DNS_OPCODE_QUERY);
2606        assert!(is_standard_query(&query));
2607        let result = validate_dns_packet(&query);
2608        assert!(result.is_ok());
2609
2610        // Test update query (opcode 5)
2611        let update_query = create_test_query_with_opcode(DNS_OPCODE_UPDATE);
2612        assert_eq!(opcode(&update_query), DNS_OPCODE_UPDATE);
2613        assert!(!is_standard_query(&update_query));
2614        let result = validate_dns_packet(&update_query);
2615        assert!(result.is_err());
2616        match result {
2617            Err(DnsError::UnsupportedOperation(msg)) => {
2618                assert!(msg.contains("Unsupported opcode: 5"));
2619            }
2620            _ => panic!("Expected UnsupportedOperation error"),
2621        }
2622    }
2623
2624    #[test]
2625    fn test_domain_name_validation() {
2626        // Test valid domain names
2627        let valid_labels = [
2628            "example",
2629            "test123",
2630            "a-valid-label",
2631            "123valid",
2632            "valid123",
2633        ];
2634
2635        for label in &valid_labels {
2636            // Check first character
2637            assert!(is_valid_domain_name_char(
2638                label.as_bytes()[0],
2639                0,
2640                label.len()
2641            ));
2642
2643            // Check last character
2644            assert!(is_valid_domain_name_char(
2645                label.as_bytes()[label.len() - 1],
2646                label.len() - 1,
2647                label.len()
2648            ));
2649
2650            // Check all characters in the label
2651            let label_bytes = label.as_bytes();
2652            let label_len = label_bytes.len();
2653            let mut is_valid = true;
2654
2655            // Check if the label is empty
2656            if label_len == 0 {
2657                is_valid = false;
2658            }
2659
2660            // Check if the label is too long
2661            if label_len > 63 {
2662                is_valid = false;
2663            }
2664
2665            // Check each character in the label
2666            for (i, &c) in label_bytes.iter().enumerate() {
2667                if !is_valid_domain_name_char(c, i, label_len) {
2668                    is_valid = false;
2669                    break;
2670                }
2671            }
2672
2673            assert!(is_valid, "Label '{}' should be valid", label);
2674        }
2675
2676        // Test invalid domain names
2677        let invalid_labels = [
2678            "-invalid",      // Starts with hyphen
2679            "invalid-",      // Ends with hyphen
2680            "inva@lid",      // Contains invalid character
2681            "invalid label", // Contains space
2682            "",              // Empty label
2683        ];
2684
2685        for label in &invalid_labels {
2686            if !label.is_empty() {
2687                if label.starts_with('-') {
2688                    assert!(!is_valid_domain_name_char(
2689                        label.as_bytes()[0],
2690                        0,
2691                        label.len()
2692                    ));
2693                }
2694                if label.ends_with('-') {
2695                    assert!(!is_valid_domain_name_char(
2696                        label.as_bytes()[label.len() - 1],
2697                        label.len() - 1,
2698                        label.len()
2699                    ));
2700                }
2701            }
2702
2703            // Check all characters in the label
2704            let label_bytes = label.as_bytes();
2705            let label_len = label_bytes.len();
2706            let mut is_valid = true;
2707
2708            // Check if the label is empty
2709            if label_len == 0 {
2710                is_valid = false;
2711            } else {
2712                // Check if the label is too long
2713                if label_len > 63 {
2714                    is_valid = false;
2715                }
2716
2717                // Check each character in the label
2718                for (i, &c) in label_bytes.iter().enumerate() {
2719                    if !is_valid_domain_name_char(c, i, label_len) {
2720                        is_valid = false;
2721                        break;
2722                    }
2723                }
2724            }
2725
2726            assert!(!is_valid, "Label '{}' should be invalid", label);
2727        }
2728    }
2729
2730    #[test]
2731    fn test_extract_edns_version() {
2732        // Test query without OPT record
2733        let query = create_test_query();
2734        let version = extract_edns_version(&query).unwrap();
2735        assert_eq!(version, None);
2736
2737        // Test query with EDNS version 0
2738        let mut query_with_edns = query.clone();
2739        add_edns_section(&mut query_with_edns, 1232).unwrap();
2740        let version = extract_edns_version(&query_with_edns).unwrap();
2741        assert_eq!(version, Some(0));
2742
2743        // Test query with EDNS version 1
2744        // Create a custom OPT record with version 1
2745        let mut query_with_edns_v1 = create_test_query();
2746
2747        // Manually add OPT record with version 1
2748        // OPT record structure:
2749        // - Name: 0 (root)
2750        // - Type: 41 (OPT)
2751        // - Class: UDP payload size
2752        // - TTL: Extended RCODE (byte 0), Version (byte 1), Flags (bytes 2-3)
2753        // - RDLEN: 0
2754        // - RDATA: empty
2755        let opt_record: Vec<u8> = vec![
2756            0, // Root domain name
2757            0, 41, // Type = OPT
2758            0x04, 0xd0, // Class = 1232 (UDP payload size)
2759            0,    // Extended RCODE
2760            1,    // EDNS Version = 1
2761            0, 0, // Flags
2762            0, 0, // RDLEN = 0
2763        ];
2764
2765        // Update ARCOUNT
2766        let arcount_offset = 10;
2767        assert!(
2768            query_with_edns_v1.len() >= arcount_offset + 2,
2769            "Packet too short for ARCOUNT"
2770        );
2771        let arcount = BigEndian::read_u16(&query_with_edns_v1[arcount_offset..arcount_offset + 2]);
2772        BigEndian::write_u16(
2773            &mut query_with_edns_v1[arcount_offset..arcount_offset + 2],
2774            arcount + 1,
2775        );
2776
2777        // Append OPT record
2778        query_with_edns_v1.extend_from_slice(&opt_record);
2779
2780        let version = extract_edns_version(&query_with_edns_v1).unwrap();
2781        assert_eq!(version, Some(1));
2782    }
2783
2784    #[test]
2785    fn test_validate_dns_packet_with_edns_version() {
2786        // Test that EDNS version 0 is accepted
2787        let mut query = create_test_query();
2788        add_edns_section(&mut query, 1232).unwrap();
2789        let result = validate_dns_packet(&query);
2790        assert!(result.is_ok());
2791
2792        // Test that EDNS version 1 is rejected
2793        let mut query_with_edns_v1 = create_test_query();
2794
2795        // Manually add OPT record with version 1
2796        let opt_record: Vec<u8> = vec![
2797            0, // Root domain name
2798            0, 41, // Type = OPT
2799            0x04, 0xd0, // Class = 1232 (UDP payload size)
2800            0,    // Extended RCODE
2801            1,    // EDNS Version = 1
2802            0, 0, // Flags
2803            0, 0, // RDLEN = 0
2804        ];
2805
2806        // Update ARCOUNT
2807        let arcount_offset = 10;
2808        assert!(
2809            query_with_edns_v1.len() >= arcount_offset + 2,
2810            "Packet too short for ARCOUNT"
2811        );
2812        let arcount = BigEndian::read_u16(&query_with_edns_v1[arcount_offset..arcount_offset + 2]);
2813        BigEndian::write_u16(
2814            &mut query_with_edns_v1[arcount_offset..arcount_offset + 2],
2815            arcount + 1,
2816        );
2817
2818        // Append OPT record
2819        query_with_edns_v1.extend_from_slice(&opt_record);
2820
2821        let result = validate_dns_packet(&query_with_edns_v1);
2822        assert!(result.is_err());
2823        match result {
2824            Err(DnsError::UnsupportedEdnsVersion { version }) => {
2825                assert_eq!(version, 1);
2826            }
2827            _ => panic!("Expected UnsupportedEdnsVersion error"),
2828        }
2829    }
2830}
2831
2832/// Structure to hold EDNS-client-subnet information
2833#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2834#[allow(dead_code)]
2835pub struct EdnsClientSubnet {
2836    /// Address family (1 for IPv4, 2 for IPv6)
2837    pub family: u16,
2838    /// Source prefix length
2839    pub source_prefix_length: u8,
2840    /// Scope prefix length
2841    pub scope_prefix_length: u8,
2842    /// IP address (truncated to the prefix length)
2843    pub address: Vec<u8>,
2844}
2845
2846/// Removes every instance of an EDNS option, and keeps the other ones.
2847pub fn remove_edns_option(packet: &mut Vec<u8>, option_code: u16) -> DnsResult<()> {
2848    let mut offset = skip_name(packet, DNS_OFFSET_QUESTION)?;
2849    if packet.len().saturating_sub(offset) < 4 {
2850        return Err(DnsError::PacketTooShort { offset });
2851    }
2852    offset += 4;
2853    offset = traverse_rrs(
2854        packet,
2855        offset,
2856        ancount(packet) as usize + nscount(packet) as usize,
2857        |_| Ok(()),
2858    )?;
2859
2860    for _ in 0..arcount(packet) {
2861        let rr_offset = skip_name(packet, offset)?;
2862        if packet.len().saturating_sub(rr_offset) < 10 {
2863            return Err(DnsError::PacketTooShort { offset: rr_offset });
2864        }
2865        let rr_type = BigEndian::read_u16(&packet[rr_offset..rr_offset + 2]);
2866        let mut rdlen = BigEndian::read_u16(&packet[rr_offset + 8..rr_offset + 10]) as usize;
2867        let rdata_offset = rr_offset + 10;
2868        if packet.len().saturating_sub(rdata_offset) < rdlen {
2869            return Err(DnsError::InvalidRecord(
2870                "OPT record data exceeds packet".to_string(),
2871            ));
2872        }
2873
2874        if rr_type == DNS_TYPE_OPT {
2875            let mut option_offset = rdata_offset;
2876            while option_offset < rdata_offset + rdlen {
2877                if rdata_offset + rdlen - option_offset < 4 {
2878                    return Err(DnsError::InvalidEdns(
2879                        "Truncated EDNS option header".to_string(),
2880                    ));
2881                }
2882                let option_len =
2883                    BigEndian::read_u16(&packet[option_offset + 2..option_offset + 4]) as usize;
2884                let option_end = option_offset.checked_add(4 + option_len).ok_or_else(|| {
2885                    DnsError::InvalidEdns("EDNS option length overflow".to_string())
2886                })?;
2887                if option_end > rdata_offset + rdlen {
2888                    return Err(DnsError::InvalidEdns(
2889                        "EDNS option exceeds OPT record data".to_string(),
2890                    ));
2891                }
2892                if BigEndian::read_u16(&packet[option_offset..option_offset + 2]) == option_code {
2893                    packet.drain(option_offset..option_end);
2894                    rdlen -= option_end - option_offset;
2895                    continue;
2896                }
2897                option_offset = option_end;
2898            }
2899            BigEndian::write_u16(&mut packet[rr_offset + 8..rr_offset + 10], rdlen as u16);
2900        }
2901
2902        offset = rdata_offset + rdlen;
2903    }
2904
2905    Ok(())
2906}
2907
2908/// Appends a cookie to a packet that ends with an OPT record without options.
2909#[cfg(test)]
2910pub(crate) fn add_cookie(packet: &mut Vec<u8>, cookie: &[u8]) {
2911    let rdlen = packet.len() - 2;
2912    packet[rdlen..].copy_from_slice(&(4 + cookie.len() as u16).to_be_bytes());
2913    packet.extend_from_slice(&EDNS_OPTION_COOKIE.to_be_bytes());
2914    packet.extend_from_slice(&(cookie.len() as u16).to_be_bytes());
2915    packet.extend_from_slice(cookie);
2916}
2917
2918/// Removes the addresses that a referral has no business carrying.
2919///
2920/// Shared DNS hosting can add an address from one customer's zone to a referral made by
2921/// another customer's zone, and some resolvers use it.
2922///
2923/// We don't know which zone made the referral, but it always contains the parent of the
2924/// delegated name.
2925/// So in the additional section, we only keep the OPT record and the addresses under that
2926/// parent, along with their signatures.
2927///
2928/// Returns how many records were removed.
2929pub fn remove_out_of_bailiwick_glue(packet: &mut Vec<u8>) -> DnsResult<usize> {
2930    let arcount = arcount(packet);
2931    if flags(packet) & DNS_FLAGS_AA != 0
2932        || rcode(packet) != 0
2933        || qdcount(packet) != 1
2934        || ancount(packet) != 0
2935        || nscount(packet) == 0
2936        || arcount == 0
2937    {
2938        return Ok(0);
2939    }
2940
2941    let qname = name_labels(packet, DNS_OFFSET_QUESTION)?;
2942    let mut offset = skip_name(packet, DNS_OFFSET_QUESTION)? + 4;
2943    let mut delegation_depth = None;
2944    for _ in 0..nscount(packet) {
2945        let record = record_at(packet, offset)?;
2946        if record.rr_type == DNS_TYPE_NS {
2947            let owner = name_labels(packet, offset)?;
2948            if is_subdomain(&qname, &owner) {
2949                delegation_depth = delegation_depth.max(Some(owner.len()));
2950            }
2951        }
2952        offset = record.end;
2953    }
2954    let Some(depth) = delegation_depth else {
2955        return Ok(0);
2956    };
2957    let bailiwick = &qname[qname.len() - depth.saturating_sub(1)..];
2958
2959    let additional_start = offset;
2960    let mut filtered = packet[..additional_start].to_vec();
2961    let mut removed = 0u16;
2962    for _ in 0..arcount {
2963        let record = record_at(packet, offset)?;
2964        let is_address = match record.rr_type {
2965            DNS_TYPE_A | DNS_TYPE_AAAA => true,
2966            DNS_TYPE_RRSIG => {
2967                record.end - record.header >= 12
2968                    && matches!(
2969                        BigEndian::read_u16(&packet[record.header + 10..]),
2970                        DNS_TYPE_A | DNS_TYPE_AAAA
2971                    )
2972            }
2973            _ => false,
2974        };
2975        if record.rr_type == DNS_TYPE_OPT
2976            || (is_address
2977                && record.rr_class == DNS_CLASS_IN
2978                && is_subdomain(&name_labels(packet, offset)?, bailiwick))
2979        {
2980            copy_name(packet, offset, additional_start, &mut filtered)?;
2981            filtered.extend_from_slice(&packet[record.header..record.end]);
2982        } else {
2983            removed += 1;
2984        }
2985        offset = record.end;
2986    }
2987
2988    if removed == 0 {
2989        return Ok(0);
2990    }
2991    // Expanding names can make the packet bigger
2992    if filtered.len() > DNS_MAX_PACKET_SIZE {
2993        return Err(DnsError::PacketTooLarge {
2994            size: filtered.len(),
2995            max_size: DNS_MAX_PACKET_SIZE,
2996        });
2997    }
2998    set_arcount(&mut filtered, arcount - removed)?;
2999    *packet = filtered;
3000    Ok(usize::from(removed))
3001}
3002
3003struct Record {
3004    rr_type: u16,
3005    rr_class: u16,
3006    /// Where the type field starts, right after the name
3007    header: usize,
3008    end: usize,
3009}
3010
3011/// Reads the record whose name starts at `offset`.
3012fn record_at(packet: &[u8], offset: usize) -> DnsResult<Record> {
3013    let header = skip_name(packet, offset)?;
3014    if packet.len().saturating_sub(header) < 10 {
3015        return Err(DnsError::PacketTooShort { offset: header });
3016    }
3017    let end = header + 10 + BigEndian::read_u16(&packet[header + 8..]) as usize;
3018    if end > packet.len() {
3019        return Err(DnsError::InvalidRecord(
3020            "Record length would exceed packet length".to_string(),
3021        ));
3022    }
3023    Ok(Record {
3024        rr_type: BigEndian::read_u16(&packet[header..]),
3025        rr_class: BigEndian::read_u16(&packet[header + 2..]),
3026        header,
3027        end,
3028    })
3029}
3030
3031/// Splits a name into labels, following compression pointers.
3032fn name_labels(packet: &[u8], mut offset: usize) -> DnsResult<Vec<&[u8]>> {
3033    // Once skip_name() accepts the name, the loop below can't go out of bounds or run forever
3034    skip_name(packet, offset)?;
3035    let mut labels = Vec::new();
3036    loop {
3037        let len = packet[offset] as usize;
3038        if len & 0xc0 == 0xc0 {
3039            offset = ((len & 0x3f) << 8) | packet[offset + 1] as usize;
3040        } else if len == 0 {
3041            return Ok(labels);
3042        } else {
3043            labels.push(&packet[offset + 1..=offset + len]);
3044            offset += 1 + len;
3045        }
3046    }
3047}
3048
3049/// Tells whether `name` is `zone` or a name under it, ignoring case.
3050fn is_subdomain(name: &[&[u8]], zone: &[&[u8]]) -> bool {
3051    name.len() >= zone.len()
3052        && name[name.len() - zone.len()..]
3053            .iter()
3054            .zip(zone)
3055            .all(|(a, b)| a.eq_ignore_ascii_case(b))
3056}
3057
3058/// Copies a name to `out`.
3059///
3060/// Everything from `limit` on is about to move, so pointers leading there are replaced by
3061/// the labels they point to.
3062fn copy_name(packet: &[u8], mut offset: usize, limit: usize, out: &mut Vec<u8>) -> DnsResult<()> {
3063    skip_name(packet, offset)?;
3064    loop {
3065        let len = packet[offset] as usize;
3066        if len & 0xc0 == 0xc0 {
3067            let pointer = ((len & 0x3f) << 8) | packet[offset + 1] as usize;
3068            if name_ends_before(packet, pointer, limit) {
3069                out.extend_from_slice(&packet[offset..offset + 2]);
3070                return Ok(());
3071            }
3072            offset = pointer;
3073        } else {
3074            out.extend_from_slice(&packet[offset..=offset + len]);
3075            if len == 0 {
3076                return Ok(());
3077            }
3078            offset += 1 + len;
3079        }
3080    }
3081}
3082
3083/// Tells whether a name, and whatever its pointers lead to, is stored before `limit`.
3084///
3085/// The name must already have been checked with skip_name().
3086fn name_ends_before(packet: &[u8], mut offset: usize, limit: usize) -> bool {
3087    loop {
3088        if offset >= limit {
3089            return false;
3090        }
3091        let len = packet[offset] as usize;
3092        if len & 0xc0 == 0xc0 {
3093            if offset + 1 >= limit {
3094                return false;
3095            }
3096            offset = ((len & 0x3f) << 8) | packet[offset + 1] as usize;
3097        } else if len == 0 {
3098            return true;
3099        } else {
3100            offset += 1 + len;
3101        }
3102    }
3103}
3104
3105/// Checks an ECS response against the subnet in its query.
3106pub fn edns_client_subnet_matches(query: &[u8], response: &[u8]) -> DnsResult<bool> {
3107    let Some(response_ecs) = extract_edns_client_subnet(response)? else {
3108        return Ok(true);
3109    };
3110    let Some(query_ecs) = extract_edns_client_subnet(query)? else {
3111        return Ok(false);
3112    };
3113
3114    Ok(response_ecs.family == query_ecs.family
3115        && response_ecs.source_prefix_length == query_ecs.source_prefix_length
3116        && response_ecs.address == query_ecs.address)
3117}
3118
3119/// Extracts EDNS-client-subnet information from a DNS packet
3120///
3121/// This function extracts EDNS-client-subnet information from a DNS packet.
3122/// It searches for an OPT record and then looks for the EDNS-client-subnet option.
3123///
3124/// # Arguments
3125///
3126/// * `packet` - The DNS packet to extract EDNS-client-subnet information from
3127///
3128/// # Returns
3129///
3130/// * `Ok(Some(EdnsClientSubnet))` - If EDNS-client-subnet information was found
3131/// * `Ok(None)` - If no EDNS-client-subnet information was found
3132/// * `Err(e)` - If there was an error extracting the information
3133#[allow(dead_code)]
3134pub fn extract_edns_client_subnet(packet: &[u8]) -> DnsResult<Option<EdnsClientSubnet>> {
3135    // Skip the question section
3136    let mut offset = skip_name(packet, DNS_OFFSET_QUESTION)?;
3137    offset += 4; // Skip QTYPE and QCLASS
3138
3139    // Skip answer and authority sections
3140    let (ancount, nscount, arcount) = (ancount(packet), nscount(packet), arcount(packet));
3141    offset = traverse_rrs(packet, offset, ancount as usize + nscount as usize, |_| {
3142        Ok(())
3143    })?;
3144
3145    // Check additional records for OPT
3146    let mut ecs_info = None;
3147    traverse_rrs(packet, offset, arcount as usize, |rr_offset| {
3148        let qtype = BigEndian::read_u16(&packet[rr_offset..]);
3149        if qtype == DNS_TYPE_OPT {
3150            // Found OPT record, now look for EDNS-client-subnet option
3151            let rdlen = BigEndian::read_u16(&packet[rr_offset + 8..rr_offset + 10]) as usize;
3152            let rdata_offset = rr_offset + 10;
3153            let rdata_end = rdata_offset + rdlen;
3154
3155            // Parse EDNS options
3156            let mut option_offset = rdata_offset;
3157            while option_offset < rdata_end {
3158                if option_offset + 4 > rdata_end {
3159                    // Not enough space for option code and length
3160                    break;
3161                }
3162
3163                let option_code = BigEndian::read_u16(&packet[option_offset..option_offset + 2]);
3164                let option_len =
3165                    BigEndian::read_u16(&packet[option_offset + 2..option_offset + 4]) as usize;
3166                option_offset += 4;
3167
3168                if option_offset + option_len > rdata_end {
3169                    // Option length exceeds RDATA
3170                    break;
3171                }
3172
3173                if option_code == EDNS_OPTION_CLIENT_SUBNET {
3174                    // Found EDNS-client-subnet option
3175                    if option_len < 4 {
3176                        // Not enough data for family, source prefix length, and scope prefix length
3177                        break;
3178                    }
3179
3180                    let family = BigEndian::read_u16(&packet[option_offset..option_offset + 2]);
3181                    let source_prefix_length = packet[option_offset + 2];
3182                    let scope_prefix_length = packet[option_offset + 3];
3183                    let address_offset = option_offset + 4;
3184                    let address_len = option_len - 4;
3185
3186                    let max_prefix = match family {
3187                        1 => 32,
3188                        2 => 128,
3189                        _ => u8::MAX,
3190                    };
3191                    if source_prefix_length > max_prefix {
3192                        break;
3193                    }
3194
3195                    // Calculate expected address length based on prefix length
3196                    let expected_address_len = (source_prefix_length as usize).div_ceil(8);
3197                    if address_len < expected_address_len {
3198                        // Not enough address bytes
3199                        break;
3200                    }
3201
3202                    // Extract the address
3203                    let address =
3204                        packet[address_offset..address_offset + expected_address_len].to_vec();
3205
3206                    ecs_info = Some(EdnsClientSubnet {
3207                        family,
3208                        source_prefix_length,
3209                        scope_prefix_length,
3210                        address,
3211                    });
3212
3213                    break;
3214                }
3215
3216                option_offset += option_len;
3217            }
3218        }
3219        Ok(())
3220    })?;
3221
3222    Ok(ecs_info)
3223}
3224
3225#[cfg(test)]
3226mod overflow_tests {
3227    use super::*;
3228    use crate::errors::DnsError;
3229
3230    #[test]
3231    fn test_offset_overflow_in_qname() {
3232        // Create a packet where label length calculation would overflow
3233        let mut packet = vec![0u8; DNS_HEADER_SIZE + 10];
3234
3235        // Set QDCOUNT to 1
3236        packet[4] = 0;
3237        packet[5] = 1;
3238
3239        // Create a label with length 64 (invalid - must be < 64)
3240        packet[DNS_HEADER_SIZE] = 64;
3241
3242        // The qname function should handle this gracefully
3243        let result = qname(&packet);
3244        assert!(matches!(result, Err(DnsError::LabelTooLong { .. })));
3245    }
3246
3247    #[test]
3248    fn test_offset_overflow_in_skip_name() {
3249        // Test that our overflow protection works
3250        // Create a small packet
3251        let mut packet = vec![0u8; 20];
3252
3253        // Set QDCOUNT to 1
3254        packet[4] = 0;
3255        packet[5] = 1;
3256
3257        // Create a name with large label count that would cause offset overflow
3258        packet[12] = 63; // Max valid label length
3259        // Not enough space in packet for this label
3260
3261        let result = skip_name(&packet, 12);
3262        assert!(
3263            result.is_err(),
3264            "Expected error when label extends beyond packet"
3265        );
3266    }
3267
3268    #[test]
3269    fn test_dns_packet_offset_boundary() {
3270        // Test packet where offset calculations approach usize::MAX
3271        // Create a valid minimal question with proper size
3272        let mut packet = vec![0u8; DNS_HEADER_SIZE + 5]; // Need 5 bytes for minimal question
3273
3274        // Set QDCOUNT to 1
3275        packet[4] = 0;
3276        packet[5] = 1;
3277
3278        packet[DNS_HEADER_SIZE] = 0; // Root label (1 byte)
3279        packet[DNS_HEADER_SIZE + 1] = 0; // QTYPE high byte
3280        packet[DNS_HEADER_SIZE + 2] = 1; // QTYPE low byte (A record)
3281        packet[DNS_HEADER_SIZE + 3] = 0; // QCLASS high byte
3282        packet[DNS_HEADER_SIZE + 4] = 1; // QCLASS low byte (IN)
3283
3284        // This should succeed without overflow
3285        let result = validate_dns_packet(&packet);
3286        assert!(result.is_ok());
3287    }
3288
3289    #[test]
3290    fn test_ecs_helpers_reject_malformed_packets_without_panicking() {
3291        let root_query_with_opt = |rdlen: u16| {
3292            let mut packet = vec![
3293                0x12, 0x34, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
3294                0x02, 0x00, 0x01, 0x00, 0x00, 0x29, 0x04, 0xd0, 0x00, 0x00, 0x00, 0x00,
3295            ];
3296            packet.extend_from_slice(&rdlen.to_be_bytes());
3297            packet
3298        };
3299
3300        // OPT data running past the end of the packet
3301        let mut packet = root_query_with_opt(0xffff);
3302        packet.extend_from_slice(&[0x00, 0x08]);
3303        assert!(extract_edns_client_subnet(&packet).is_err());
3304
3305        // A packet already over the size limit, because of a large padding option
3306        let padding_len = DNS_MAX_PACKET_SIZE;
3307        let mut packet = root_query_with_opt((padding_len + 4) as u16);
3308        packet.extend_from_slice(&[0x00, 0x0c]);
3309        packet.extend_from_slice(&(padding_len as u16).to_be_bytes());
3310        packet.resize(packet.len() + padding_len, 0);
3311        assert!(matches!(
3312            add_edns_client_subnet(&mut packet, "192.0.2.1", 24, 56, 1232),
3313            Err(DnsError::PacketTooLarge { .. })
3314        ));
3315    }
3316}
3317
3318#[cfg(test)]
3319mod bailiwick_tests {
3320    use super::*;
3321
3322    // Mixed case, like resolvers that randomize it
3323    const QNAME: &str = "www.sub.EXAMPLE.com";
3324
3325    fn wire_name(name: &str) -> Vec<u8> {
3326        let mut out = Vec::new();
3327        for label in name.split('.').filter(|label| !label.is_empty()) {
3328            out.push(label.len() as u8);
3329            out.extend_from_slice(label.as_bytes());
3330        }
3331        out.push(0);
3332        out
3333    }
3334
3335    fn pointer(offset: usize) -> [u8; 2] {
3336        (0xc000 | offset as u16).to_be_bytes()
3337    }
3338
3339    fn rr(owner: &[u8], rr_type: u16, rdata: &[u8]) -> Vec<u8> {
3340        let mut out = owner.to_vec();
3341        out.extend_from_slice(&rr_type.to_be_bytes());
3342        out.extend_from_slice(&DNS_CLASS_IN.to_be_bytes());
3343        out.extend_from_slice(&300u32.to_be_bytes());
3344        out.extend_from_slice(&(rdata.len() as u16).to_be_bytes());
3345        out.extend_from_slice(rdata);
3346        out
3347    }
3348
3349    fn referral(authority: &[Vec<u8>], additional: &[Vec<u8>]) -> Vec<u8> {
3350        let mut packet = vec![0x12, 0x34, 0x80, 0x00, 0x00, 0x01, 0x00, 0x00];
3351        packet.extend_from_slice(&(authority.len() as u16).to_be_bytes());
3352        packet.extend_from_slice(&(additional.len() as u16).to_be_bytes());
3353        packet.extend_from_slice(&wire_name(QNAME));
3354        packet.extend_from_slice(&[0x00, 0x01, 0x00, 0x01]);
3355        for record in authority.iter().chain(additional) {
3356            packet.extend_from_slice(record);
3357        }
3358        packet
3359    }
3360
3361    /// Delegates sub.EXAMPLE.com, which is at offset 16 in the question, to `ns`.
3362    fn delegation(ns: &[u8]) -> Vec<u8> {
3363        rr(&pointer(16), DNS_TYPE_NS, ns)
3364    }
3365
3366    /// Where the data of the first NS record starts, after its name and fixed fields.
3367    fn first_ns_data() -> usize {
3368        referral(&[], &[]).len() + 12
3369    }
3370
3371    #[test]
3372    fn test_only_glue_under_the_parent_zone_is_kept() {
3373        let authority = [
3374            delegation(&wire_name("ns1.sub.example.com")),
3375            delegation(&wire_name("ns2.example.com")),
3376        ];
3377        let in_domain = rr(&pointer(first_ns_data()), DNS_TYPE_A, &[192, 0, 2, 1]);
3378        let sibling = rr(&wire_name("ns2.example.com"), DNS_TYPE_AAAA, &[0x20; 16]);
3379        let sibling_signature = rr(
3380            &wire_name("ns2.example.com"),
3381            DNS_TYPE_RRSIG,
3382            &DNS_TYPE_AAAA.to_be_bytes(),
3383        );
3384        let unrelated = rr(&wire_name("ns.example.net"), DNS_TYPE_A, &[198, 51, 100, 1]);
3385        let not_an_address = rr(&wire_name("ns1.sub.example.com"), DNS_TYPE_TXT, b"\x02hi");
3386
3387        let mut packet = referral(
3388            &authority,
3389            &[
3390                in_domain.clone(),
3391                unrelated,
3392                sibling.clone(),
3393                not_an_address,
3394                sibling_signature.clone(),
3395            ],
3396        );
3397        let mut expected = referral(&authority, &[in_domain, sibling, sibling_signature]);
3398        add_edns_section(&mut packet, 1232).unwrap();
3399        add_edns_section(&mut expected, 1232).unwrap();
3400
3401        assert_eq!(remove_out_of_bailiwick_glue(&mut packet).unwrap(), 2);
3402        assert_eq!(packet, expected);
3403    }
3404
3405    #[test]
3406    fn test_pointers_to_moved_records_are_expanded() {
3407        // The NS data stops after "ns1", so that name goes on with the name of the TXT record
3408        let authority = [delegation(b"\x03ns1")];
3409        let txt_name = pointer(referral(&authority, &[]).len());
3410        let mut packet = referral(
3411            &authority,
3412            &[
3413                rr(&wire_name("example.com"), DNS_TYPE_TXT, b"\x02hi"),
3414                rr(&pointer(first_ns_data()), DNS_TYPE_A, &[192, 0, 2, 1]),
3415                rr(
3416                    &[b"\x03ns2", &txt_name[..]].concat(),
3417                    DNS_TYPE_A,
3418                    &[192, 0, 2, 2],
3419                ),
3420            ],
3421        );
3422        assert!(validate_dns_response(&packet).is_ok());
3423
3424        let expected = referral(
3425            &authority,
3426            &[
3427                rr(&wire_name("ns1.example.com"), DNS_TYPE_A, &[192, 0, 2, 1]),
3428                rr(&wire_name("ns2.example.com"), DNS_TYPE_A, &[192, 0, 2, 2]),
3429            ],
3430        );
3431        assert_eq!(remove_out_of_bailiwick_glue(&mut packet).unwrap(), 1);
3432        assert_eq!(packet, expected);
3433    }
3434
3435    #[test]
3436    fn test_other_responses_are_left_alone() {
3437        let glue = || rr(&wire_name("ns.example.net"), DNS_TYPE_A, &[198, 51, 100, 1]);
3438        let mut authoritative = referral(&[delegation(&wire_name("ns.example.net"))], &[glue()]);
3439        set_aa(&mut authoritative, true).unwrap();
3440        let other_name = rr(
3441            &wire_name("other.example.com"),
3442            DNS_TYPE_NS,
3443            &wire_name("ns.example.net"),
3444        );
3445        let root = rr(&[0], DNS_TYPE_NS, &wire_name("a.root-servers.net"));
3446
3447        for mut packet in [
3448            authoritative,
3449            referral(&[other_name], &[glue()]),
3450            // Every name is under the root
3451            referral(&[root], &[glue()]),
3452        ] {
3453            assert_eq!(remove_out_of_bailiwick_glue(&mut packet).unwrap(), 0);
3454        }
3455    }
3456
3457    #[test]
3458    fn test_malformed_or_oversized_results_are_errors() {
3459        let authority = [delegation(&wire_name("ns.example.com"))];
3460
3461        let glue = rr(&wire_name("ns.example.net"), DNS_TYPE_A, &[198, 51, 100, 1]);
3462        let mut truncated = referral(&authority, &[glue]);
3463        truncated.pop();
3464        assert!(remove_out_of_bailiwick_glue(&mut truncated).is_err());
3465
3466        // Once the TXT record is gone, its long name has to be written out in all 30 A records
3467        let long_name = format!("{}example.com", "abcdefghijklmnopqrstuvwxyz.".repeat(8));
3468        let a_long_name = [b"\x01a", &pointer(referral(&authority, &[]).len())[..]].concat();
3469        let mut additional = vec![rr(&wire_name(&long_name), DNS_TYPE_TXT, b"\x02hi")];
3470        additional.extend(std::iter::repeat_n(
3471            rr(&a_long_name, DNS_TYPE_A, &[192, 0, 2, 3]),
3472            30,
3473        ));
3474        let mut too_large = referral(&authority, &additional);
3475        assert!(validate_dns_response(&too_large).is_ok());
3476        assert!(matches!(
3477            remove_out_of_bailiwick_glue(&mut too_large),
3478            Err(DnsError::PacketTooLarge { .. })
3479        ));
3480    }
3481}