dns-resolver-rs 0.1.1

A simple DNS resolver server built with Axum and Tokio
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
mod cache;
pub mod server;

use crate::cache::{DOMAIN_TO_IP_CACHE, IP_TO_DOMAIN_CACHE};
use anyhow::Result;
use num_enum::TryFromPrimitive;
use rand::random;
use std::net::Ipv4Addr;
use tokio::net::UdpSocket;
use tokio::time::{Duration, timeout};
use tracing::info;

#[derive(Debug, Clone)]
struct DNSHeader {
    id: u16,
    flags: u16,
    num_questions: u16,
    num_answers: u16,
    num_authorities: u16,
    num_additionals: u16,
}

impl DNSHeader {
    fn new(flags: u16, num_questions: u16) -> Self {
        DNSHeader {
            id: random(),
            flags,
            num_questions,
            num_answers: 0,
            num_authorities: 0,
            num_additionals: 0,
        }
    }

    fn to_bytes(&self) -> Vec<u8> {
        [
            self.id.to_be_bytes(),
            self.flags.to_be_bytes(),
            self.num_questions.to_be_bytes(),
            self.num_answers.to_be_bytes(),
            self.num_authorities.to_be_bytes(),
            self.num_additionals.to_be_bytes(),
        ]
        .concat()
    }

    fn parse(bytes: &[u8]) -> Result<Self> {
        Ok(Self {
            id: u16::from_be_bytes(bytes[0..2].try_into()?),
            flags: u16::from_be_bytes(bytes[2..4].try_into()?),
            num_questions: u16::from_be_bytes(bytes[4..6].try_into()?),
            num_answers: u16::from_be_bytes(bytes[6..8].try_into()?),
            num_authorities: u16::from_be_bytes(bytes[8..10].try_into()?),
            num_additionals: u16::from_be_bytes(bytes[10..12].try_into()?),
        })
    }
}

#[derive(Debug, Clone, Default, TryFromPrimitive, PartialEq)]
#[repr(u16)]
enum RecordType {
    #[default]
    A = 1,
    Ns = 2,
    Md = 3,
    Mf = 4,
    Cname = 5,
    Soa = 6,
    Ptr = 12,
    Aaaa = 28,
}

#[derive(Debug, Clone, Default, TryFromPrimitive, PartialEq)]
#[repr(u16)]
enum Class {
    #[default]
    In = 1,
}

#[derive(Debug, Clone)]
struct DNSQuestion {
    name: String,
    type_: RecordType,
    class: Class,
}

impl DNSQuestion {
    fn new(name: String, type_: RecordType, class: Class) -> Self {
        Self { name, type_, class }
    }
    fn to_bytes(&self) -> Vec<u8> {
        [
            self.name.as_bytes(),
            &(self.type_.clone() as u16).to_be_bytes(),
            &(self.class.clone() as u16).to_be_bytes(),
        ]
        .concat()
    }

    fn parse(buf: &[u8], cursor_start: usize) -> Result<(Self, usize)> {
        let mut cursor = cursor_start;
        let (name, length) = decode_name(buf, cursor);
        cursor += length;
        Ok((
            Self {
                name,
                type_: RecordType::try_from(u16::from_be_bytes(
                    buf[cursor..cursor + 2].try_into()?,
                ))
                .unwrap(),
                class: Class::try_from(u16::from_be_bytes(buf[cursor + 2..cursor + 4].try_into()?))
                    .unwrap(),
            },
            cursor + 4 - cursor_start,
        ))
    }
}

fn decode_name(buf: &[u8], cursor_start: usize) -> (String, usize) {
    let mut cursor = cursor_start;
    let mut length = buf[cursor] as usize;
    let mut components = Vec::new();
    while length != 0 {
        if length & 0b11000000 != 0 {
            // DNS component max length is 63 bytes so in case first 2 bits are set,
            // then takes the bottom 6 bits of the length byte, plus the next byte,
            // and converts that to a pointer.
            components.push(decode_compressed_name(buf, cursor));
            cursor += 2;
            return (components.join("."), cursor - cursor_start);
        } else {
            let start = cursor + 1;
            cursor += length + 1;
            components.push(String::from_utf8_lossy(&buf[start..cursor]).into_owned());
            length = buf[cursor] as usize;
        }
    }
    // Added one for the zero at the end
    cursor += 1;
    (components.join("."), cursor - cursor_start)
}

fn decode_compressed_name(buf: &[u8], cursor_start: usize) -> String {
    let cursor =
        u16::from_be_bytes([(buf[cursor_start] & 0b00111111), buf[cursor_start + 1]]) as usize;
    decode_name(buf, cursor).0
}

#[allow(unused)]
#[derive(Debug, Clone)]
enum DNSRecordData {
    Data(Vec<u8>),
    Name(String),
    Ipv4Addr(Ipv4Addr),
}

#[allow(unused)]
#[derive(Debug, Clone)]
struct DNSRecord {
    name: String,
    type_: RecordType,
    class: Class,
    ttl: u32,
    data: DNSRecordData,
}

impl DNSRecord {
    fn parse(buf: &[u8], start_cursor: usize) -> Result<(Self, usize)> {
        let mut cursor = start_cursor;
        let (name, length) = decode_name(buf, cursor);
        cursor += length;
        let type_ =
            RecordType::try_from(u16::from_be_bytes(buf[cursor..cursor + 2].try_into()?)).unwrap();
        let class =
            Class::try_from(u16::from_be_bytes(buf[cursor + 2..cursor + 4].try_into()?)).unwrap();
        let ttl = u32::from_be_bytes(buf[cursor + 4..cursor + 8].try_into()?);
        let data_len = u16::from_be_bytes(buf[cursor + 8..cursor + 10].try_into()?) as usize;
        cursor += 10;
        let data = match type_ {
            RecordType::A => {
                let ip = Ipv4Addr::new(
                    buf[cursor],
                    buf[cursor + 1],
                    buf[cursor + 2],
                    buf[cursor + 3],
                );
                cursor += 4;
                DNSRecordData::Ipv4Addr(ip)
            }
            RecordType::Ns | RecordType::Cname | RecordType::Ptr => {
                let (name, len) = decode_name(buf, cursor);
                cursor += len;
                DNSRecordData::Name(name)
            }
            _ => {
                let data = buf[cursor..cursor + data_len].to_vec();
                cursor += data_len;
                DNSRecordData::Data(data)
            }
        };
        Ok((
            Self {
                name,
                type_,
                class,
                ttl,
                data,
            },
            cursor - start_cursor,
        ))
    }
}

#[allow(unused)]
#[derive(Debug, Clone)]
pub struct DNSPacket {
    header: DNSHeader,
    questions: Vec<DNSQuestion>,
    answers: Vec<DNSRecord>,
    authorities: Vec<DNSRecord>,
    additionals: Vec<DNSRecord>,
}

impl DNSPacket {
    fn parse(buf: &[u8]) -> Result<Self> {
        let header = DNSHeader::parse(buf)?;
        const DNS_HEADER_LEN: usize = 12;
        let mut cursor = DNS_HEADER_LEN;
        let mut questions = Vec::new();
        for _ in 0..header.num_questions {
            let (question, length) = DNSQuestion::parse(buf, cursor)?;
            questions.push(question);
            cursor += length;
        }

        let mut answers = Vec::new();
        for _ in 0..header.num_answers {
            let (answer, length) = DNSRecord::parse(buf, cursor)?;
            answers.push(answer);
            cursor += length;
        }

        let mut authorities = Vec::new();
        for _ in 0..header.num_authorities {
            let (authority, length) = DNSRecord::parse(buf, cursor)?;
            authorities.push(authority);
            cursor += length;
        }

        let mut additionals = Vec::new();
        for _ in 0..header.num_additionals {
            let (additional, length) = DNSRecord::parse(buf, cursor)?;
            additionals.push(additional);
            cursor += length;
        }
        Ok(Self {
            header,
            questions,
            answers,
            authorities,
            additionals,
        })
    }

    fn get_answer_ip(&self) -> Option<Ipv4Addr> {
        for answer in &self.answers {
            if let DNSRecordData::Ipv4Addr(name) = answer.data {
                return Some(name);
            }
        }
        None
    }

    fn get_answer_domain(&self) -> Option<&str> {
        for answer in &self.answers {
            if let DNSRecordData::Name(name) = &answer.data {
                return Some(name.as_str());
            }
        }
        None
    }

    fn get_nameserver_ip(&self) -> Option<Ipv4Addr> {
        for record in &self.additionals {
            if let DNSRecordData::Ipv4Addr(ip) = record.data {
                return Some(ip);
            }
        }
        None
    }

    fn get_nameserver_domain(&self) -> Option<&str> {
        for record in &self.authorities {
            if let DNSRecordData::Name(name) = &record.data {
                return Some(name.as_str());
            }
        }
        None
    }
}

#[derive(Debug, Clone)]
pub struct DNSResolver {
    id_addr: Ipv4Addr,
}

impl Default for DNSResolver {
    fn default() -> Self {
        DNSResolver::new("198.41.0.4")
    }
}

impl DNSResolver {
    pub fn new(id_addr: &str) -> Self {
        DNSResolver {
            id_addr: id_addr.parse::<Ipv4Addr>().unwrap(),
        }
    }

    fn encode_dns_name(name: &str) -> Vec<u8> {
        let mut encoded = Vec::new();
        for component in name.split('.') {
            encoded.push(component.len() as u8);
            encoded.extend(component.as_bytes());
        }
        encoded.push(0);
        encoded
    }

    fn build_query(domain_name: &str, record_type: RecordType, class: Class) -> Vec<u8> {
        let encoded_name = Self::encode_dns_name(domain_name);
        let header = DNSHeader::new(0, 1).to_bytes();
        let questions =
            DNSQuestion::new(String::from_utf8(encoded_name).unwrap(), record_type, class)
                .to_bytes();
        [header, questions].concat()
    }

    async fn lookup(
        domain_name: &str,
        ip_addr: &Ipv4Addr,
        record_type: RecordType,
    ) -> Result<DNSPacket> {
        info!("Querying {ip_addr} for {domain_name}");
        let query = Self::build_query(domain_name, record_type, Class::In);
        let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await?;
        socket.send_to(&query, (*ip_addr, 53)).await?;

        let mut buf = [0; 1024];
        let recv_result = timeout(Duration::from_secs(5), socket.recv_from(&mut buf)).await;
        let size = match recv_result {
            Ok(Ok((size, _src))) => size,
            Ok(Err(e)) => return Err(e.into()),
            Err(_) => return Err(anyhow::anyhow!("Timed out waiting for response")),
        };
        DNSPacket::parse(&buf[..size])
    }

    pub async fn resolve(&self, domain_name: &str) -> Result<Ipv4Addr> {
        if let Some(ip) = DOMAIN_TO_IP_CACHE.get(domain_name).await {
            return Ok(ip);
        }
        let mut ip_addr = self.id_addr;
        loop {
            let dns_packet = Self::lookup(domain_name, &ip_addr, RecordType::A).await?;
            if let Some(ip) = dns_packet.get_answer_ip() {
                DOMAIN_TO_IP_CACHE.insert(domain_name.to_string(), ip).await;
                return Ok(ip);
            } else if let Some(name) = dns_packet.get_answer_domain() {
                return Box::pin(self.resolve(name)).await;
            } else if let Some(ns_ip) = dns_packet.get_nameserver_ip() {
                ip_addr = ns_ip;
            } else if let Some(name) = dns_packet.get_nameserver_domain() {
                ip_addr = Box::pin(self.resolve(name)).await?;
            } else {
                anyhow::bail!("Could not resolve DNS domain name");
            }
        }
    }

    pub async fn reverse_resolve(&self, req_ip_addr: &Ipv4Addr) -> Result<String> {
        if let Some(domain) = IP_TO_DOMAIN_CACHE.get(req_ip_addr).await {
            return Ok(domain);
        }
        let mut ns_ip_addr = self.id_addr;
        let ip_addr = req_ip_addr.octets();
        let ip_domain = format!(
            "{}.{}.{}.{}.in-addr.arpa",
            ip_addr[3], ip_addr[2], ip_addr[1], ip_addr[0]
        );
        loop {
            let dns_packet = Self::lookup(&ip_domain, &ns_ip_addr, RecordType::Ptr).await?;
            if let Some(domain) = dns_packet.get_answer_domain() {
                IP_TO_DOMAIN_CACHE
                    .insert(*req_ip_addr, domain.to_string())
                    .await;
                return Ok(domain.to_string());
            } else if let Some(ns_ip) = dns_packet.get_nameserver_ip() {
                ns_ip_addr = ns_ip;
            } else if let Some(name) = dns_packet.get_nameserver_domain() {
                ns_ip_addr = self.resolve(name).await?;
            } else {
                anyhow::bail!("Could not reverse resolve the ip addr");
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{Class, DNSResolver, RecordType, decode_name};

    #[test]
    fn test_encode_dns_name() {
        assert_eq!(
            DNSResolver::encode_dns_name("google.com"),
            b"\x06google\x03com\x00"
        );
    }

    #[test]
    fn test_class() {
        assert_eq!(Class::In as u16, 1);
        assert_eq!(Class::try_from(1).unwrap(), Class::In);
    }

    #[test]
    fn test_record_type() {
        assert_eq!(RecordType::A as u16, 1);
        assert_eq!(RecordType::Ns as u16, 2);
        assert_eq!(RecordType::Md as u16, 3);
        assert_eq!(RecordType::Mf as u16, 4);

        assert_eq!(RecordType::try_from(1).unwrap(), RecordType::A);
        assert_eq!(RecordType::try_from(2).unwrap(), RecordType::Ns);
        assert_eq!(RecordType::try_from(3).unwrap(), RecordType::Md);
        assert_eq!(RecordType::try_from(4).unwrap(), RecordType::Mf);
    }

    #[test]
    fn test_build_query() {
        // validate after the random id
        assert_eq!(
            &DNSResolver::build_query("example.com", RecordType::A, Class::In)[2..],
            b"\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x07example\x03com\x00\x00\x01\x00\x01"
        );
    }

    #[test]
    fn test_decode_name() {
        let mut buf = [0; 17];
        buf[0] = 3;
        buf[1] = 'w' as u8;
        buf[2] = 'w' as u8;
        buf[3] = 'w' as u8;
        buf[4] = 7;
        buf[5] = 'e' as u8;
        buf[6] = 'x' as u8;
        buf[7] = 'a' as u8;
        buf[8] = 'm' as u8;
        buf[9] = 'p' as u8;
        buf[10] = 'l' as u8;
        buf[11] = 'e' as u8;
        buf[12] = 3;
        buf[13] = 'c' as u8;
        buf[14] = 'o' as u8;
        buf[15] = 'm' as u8;
        buf[16] = 0;

        let (name, usize) = decode_name(&buf, 0);
        assert_eq!(name, "www.example.com");
        assert_eq!(usize as usize, 17);
    }
}