1#![allow(dead_code)]
7
8pub const FLAG_QR_RESPONSE: u16 = 0x8000;
10pub const OPCODE_MASK: u16 = 0x7800;
11pub const FLAG_AA_AUTHORITATIVE: u16 = 0x0400;
12pub const FLAG_TC_TRUNCATED: u16 = 0x0200;
13pub const FLAG_RD_RECURSION_DESIRED: u16 = 0x0100;
14pub const FLAG_RA_RECURSION_AVAILABLE: u16 = 0x0080;
15pub const FLAG_AD_AUTHENTICATED_DATA: u16 = 0x0020;
16pub const FLAG_CD_CHECKING_DISABLED: u16 = 0x0010;
17pub const RCODE_MASK: u16 = 0x000F;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21#[repr(u16)]
22pub enum DnsType {
23 A = 1,
24 NS = 2,
25 CNAME = 5,
26 SOA = 6,
27 PTR = 12,
28 MX = 15,
29 TXT = 16,
30 AAAA = 28,
31 SRV = 33,
32 CERT = 37,
33 OPT = 41,
34 DS = 43,
35 RRSIG = 46,
36 NSEC = 47,
37 DNSKEY = 48,
38 NSEC3 = 50,
39 TLSA = 52,
40 SVCB = 64,
41 HTTPS = 65,
42 CAA = 257,
43 Unknown(u16),
44}
45
46impl From<u16> for DnsType {
47 fn from(val: u16) -> Self {
48 match val {
49 1 => Self::A,
50 2 => Self::NS,
51 5 => Self::CNAME,
52 6 => Self::SOA,
53 12 => Self::PTR,
54 15 => Self::MX,
55 16 => Self::TXT,
56 28 => Self::AAAA,
57 33 => Self::SRV,
58 37 => Self::CERT,
59 41 => Self::OPT,
60 43 => Self::DS,
61 46 => Self::RRSIG,
62 47 => Self::NSEC,
63 48 => Self::DNSKEY,
64 50 => Self::NSEC3,
65 52 => Self::TLSA,
66 64 => Self::SVCB,
67 65 => Self::HTTPS,
68 257 => Self::CAA,
69 other => Self::Unknown(other),
70 }
71 }
72}
73
74impl From<DnsType> for u16 {
75 fn from(t: DnsType) -> Self {
76 match t {
77 DnsType::A => 1,
78 DnsType::NS => 2,
79 DnsType::CNAME => 5,
80 DnsType::SOA => 6,
81 DnsType::PTR => 12,
82 DnsType::MX => 15,
83 DnsType::TXT => 16,
84 DnsType::AAAA => 28,
85 DnsType::SRV => 33,
86 DnsType::CERT => 37,
87 DnsType::OPT => 41,
88 DnsType::DS => 43,
89 DnsType::RRSIG => 46,
90 DnsType::NSEC => 47,
91 DnsType::DNSKEY => 48,
92 DnsType::NSEC3 => 50,
93 DnsType::TLSA => 52,
94 DnsType::SVCB => 64,
95 DnsType::HTTPS => 65,
96 DnsType::CAA => 257,
97 DnsType::Unknown(other) => other,
98 }
99 }
100}
101
102pub const CLASS_IN: u16 = 1;
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107#[repr(C)]
108pub struct DnsHeader {
109 pub id: u16,
110 pub flags: u16,
111 pub qdcount: u16,
112 pub ancount: u16,
113 pub nscount: u16,
114 pub arcount: u16,
115}
116
117impl DnsHeader {
118 pub const SIZE: usize = 12;
119
120 pub fn new_query(id: u16, recursion_desired: bool) -> Self {
122 let mut flags = 0u16;
123 if recursion_desired {
124 flags |= FLAG_RD_RECURSION_DESIRED;
125 }
126 Self {
127 id,
128 flags,
129 qdcount: 1,
130 ancount: 0,
131 nscount: 0,
132 arcount: 0,
133 }
134 }
135
136 pub fn encode(&self, out: &mut [u8]) -> Result<usize, &'static str> {
138 if out.len() < Self::SIZE {
139 return Err("buffer too small for DNS header");
140 }
141 out[0..2].copy_from_slice(&self.id.to_be_bytes());
142 out[2..4].copy_from_slice(&self.flags.to_be_bytes());
143 out[4..6].copy_from_slice(&self.qdcount.to_be_bytes());
144 out[6..8].copy_from_slice(&self.ancount.to_be_bytes());
145 out[8..10].copy_from_slice(&self.nscount.to_be_bytes());
146 out[10..12].copy_from_slice(&self.arcount.to_be_bytes());
147 Ok(Self::SIZE)
148 }
149
150 pub fn decode(src: &[u8]) -> Result<Self, &'static str> {
152 if src.len() < Self::SIZE {
153 return Err("buffer too short for DNS header");
154 }
155 Ok(Self {
156 id: u16::from_be_bytes([src[0], src[1]]),
157 flags: u16::from_be_bytes([src[2], src[3]]),
158 qdcount: u16::from_be_bytes([src[4], src[5]]),
159 ancount: u16::from_be_bytes([src[6], src[7]]),
160 nscount: u16::from_be_bytes([src[8], src[9]]),
161 arcount: u16::from_be_bytes([src[10], src[11]]),
162 })
163 }
164
165 pub fn is_response(&self) -> bool {
167 (self.flags & FLAG_QR_RESPONSE) != 0
168 }
169
170 pub fn is_authenticated_data(&self) -> bool {
172 (self.flags & FLAG_AD_AUTHENTICATED_DATA) != 0
173 }
174
175 pub fn rcode(&self) -> u8 {
177 (self.flags & RCODE_MASK) as u8
178 }
179}
180
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
183pub struct DnsQuestion<'a> {
184 pub name: &'a [u8],
185 pub qtype: DnsType,
186 pub qclass: u16,
187}
188
189pub fn encode_domain_name(name: &str, out: &mut [u8]) -> Result<usize, &'static str> {
191 let mut offset = 0;
192 for label in name.split('.') {
193 if label.is_empty() {
194 continue;
195 }
196 let len = label.len();
197 if len > 63 {
198 return Err("DNS label exceeds 63 bytes");
199 }
200 if offset + 1 + len >= out.len() {
201 return Err("DNS name buffer overflow");
202 }
203 out[offset] = len as u8;
204 offset += 1;
205 out[offset..offset + len].copy_from_slice(label.as_bytes());
206 offset += len;
207 }
208 if offset >= out.len() {
209 return Err("DNS name buffer overflow on null terminator");
210 }
211 out[offset] = 0;
212 offset += 1;
213 Ok(offset)
214}
215
216pub fn decode_domain_name(
218 packet: &[u8],
219 mut offset: usize,
220 out_buf: &mut [u8],
221) -> Result<(usize, usize), &'static str> {
222 let mut out_pos = 0;
223 let mut jumps = 0usize;
224 let mut next_offset = None;
225
226 loop {
227 if offset >= packet.len() {
228 return Err("DNS name offset out of bounds");
229 }
230 let len = packet[offset];
231 if len == 0 {
232 if next_offset.is_none() {
233 next_offset = Some(offset + 1);
234 }
235 break;
236 }
237
238 if (len & 0xC0) == 0xC0 {
240 if offset + 1 >= packet.len() {
241 return Err("DNS compression pointer truncated");
242 }
243 if next_offset.is_none() {
244 next_offset = Some(offset + 2);
245 }
246 let pointer = (((len & 0x3F) as usize) << 8) | (packet[offset + 1] as usize);
247 offset = pointer;
248 jumps += 1;
249 if jumps > 16 {
250 return Err("DNS compression pointer loop detected");
251 }
252 continue;
253 }
254
255 offset += 1;
256 let label_len = len as usize;
257 if offset + label_len > packet.len() {
258 return Err("DNS label length truncated");
259 }
260 if out_pos > 0 {
261 if out_pos >= out_buf.len() {
262 return Err("decoded name buffer overflow");
263 }
264 out_buf[out_pos] = b'.';
265 out_pos += 1;
266 }
267 if out_pos + label_len > out_buf.len() {
268 return Err("decoded name buffer overflow");
269 }
270 out_buf[out_pos..out_pos + label_len].copy_from_slice(&packet[offset..offset + label_len]);
271 out_pos += label_len;
272 offset += label_len;
273 }
274
275 let consumed = next_offset.unwrap_or(offset);
276 Ok((consumed, out_pos))
277}
278
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
281pub struct DnsRecordView<'a> {
282 pub rtype: DnsType,
283 pub rclass: u16,
284 pub ttl: u32,
285 pub rdata: &'a [u8],
286 pub rdata_offset: usize,
287 pub packet: &'a [u8],
288}
289
290pub fn parse_records<'a, F>(
292 packet: &'a [u8],
293 mut offset: usize,
294 count: usize,
295 mut callback: F,
296) -> Result<usize, &'static str>
297where
298 F: FnMut(&str, DnsRecordView<'a>) -> Result<(), &'static str>,
299{
300 let mut name_buf = [0u8; 256];
301 for _ in 0..count {
302 if offset >= packet.len() {
303 return Err("unexpected EOF in DNS records");
304 }
305 let (new_offset, name_len) = decode_domain_name(packet, offset, &mut name_buf)?;
306 offset = new_offset;
307
308 if offset + 10 > packet.len() {
309 return Err("DNS record header truncated");
310 }
311 let rtype = DnsType::from(u16::from_be_bytes([packet[offset], packet[offset + 1]]));
312 let rclass = u16::from_be_bytes([packet[offset + 2], packet[offset + 3]]);
313 let ttl = u32::from_be_bytes([
314 packet[offset + 4],
315 packet[offset + 5],
316 packet[offset + 6],
317 packet[offset + 7],
318 ]);
319 let rdlength = u16::from_be_bytes([packet[offset + 8], packet[offset + 9]]) as usize;
320 offset += 10;
321
322 if offset + rdlength > packet.len() {
323 return Err("DNS RDATA truncated");
324 }
325 let rdata_offset = offset;
326 let rdata = &packet[offset..offset + rdlength];
327 offset += rdlength;
328
329 let name_str =
330 std::str::from_utf8(&name_buf[..name_len]).map_err(|_| "invalid UTF-8 in DNS name")?;
331 callback(
332 name_str,
333 DnsRecordView {
334 rtype,
335 rclass,
336 ttl,
337 rdata,
338 rdata_offset,
339 packet,
340 },
341 )?;
342 }
343 Ok(offset)
344}
345
346pub fn build_query_packet(
348 id: u16,
349 domain: &str,
350 qtype: DnsType,
351 recursion_desired: bool,
352 out: &mut [u8],
353) -> Result<usize, &'static str> {
354 let header = DnsHeader::new_query(id, recursion_desired);
355 let mut offset = header.encode(out)?;
356
357 let name_len = encode_domain_name(domain, &mut out[offset..])?;
358 offset += name_len;
359
360 if offset + 4 > out.len() {
361 return Err("buffer too small for DNS question type and class");
362 }
363 out[offset..offset + 2].copy_from_slice(&u16::from(qtype).to_be_bytes());
364 out[offset + 2..offset + 4].copy_from_slice(&CLASS_IN.to_be_bytes());
365 offset += 4;
366
367 Ok(offset)
368}
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373
374 #[test]
375 fn header_roundtrip() {
376 let h = DnsHeader::new_query(0x1234, true);
377 let mut buf = [0u8; 12];
378 let n = h.encode(&mut buf).unwrap();
379 assert_eq!(n, 12);
380 let decoded = DnsHeader::decode(&buf).unwrap();
381 assert_eq!(decoded.id, 0x1234);
382 assert_eq!(
383 decoded.flags & FLAG_RD_RECURSION_DESIRED,
384 FLAG_RD_RECURSION_DESIRED
385 );
386 assert_eq!(decoded.qdcount, 1);
387 }
388
389 #[test]
390 fn domain_encode_decode() {
391 let mut wire = [0u8; 64];
392 let n = encode_domain_name("sub.domain.example.org", &mut wire).unwrap();
393 assert!(n > 0);
394
395 let mut decoded = [0u8; 64];
396 let (consumed, len) = decode_domain_name(&wire, 0, &mut decoded).unwrap();
397 assert_eq!(consumed, n);
398 let s = std::str::from_utf8(&decoded[..len]).unwrap();
399 assert_eq!(s, "sub.domain.example.org");
400 }
401
402 #[test]
403 fn query_packet_builder() {
404 let mut pkt = [0u8; 512];
405 let len = build_query_packet(42, "example.com", DnsType::TXT, true, &mut pkt).unwrap();
406 assert!(len > 12);
407
408 let h = DnsHeader::decode(&pkt).unwrap();
409 assert_eq!(h.id, 42);
410 assert_eq!(h.qdcount, 1);
411 }
412}