rustdns 0.7.0

A DNS parsing library
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
use crate::bail;
use crate::io::{CursorExt, DNSReadExt, SeekExt};
use crate::types::*;
use crate::ParseError;
use byteorder::{ReadBytesExt, BE};
use std::convert::TryFrom;
use std::io;
use std::io::Cursor;
use std::io::Read;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::time::Duration;

/// IPv4 Address (A) record.
pub type A = Ipv4Addr;

/// IPv6 Address (AAAA) record.
#[allow(clippy::upper_case_acronyms)]
pub type AAAA = Ipv6Addr;

/// Name Server (NS) record for delegating a the given authoritative name
/// servers.
pub type NS = String;

/// Canonical name (CNAME) record, for aliasing one name to another.
#[allow(clippy::upper_case_acronyms)]
pub type CNAME = String;

/// Pointer (PTR) record most commonly used for most common use is for
/// implementing reverse DNS lookups.
#[allow(clippy::upper_case_acronyms)]
pub type PTR = String;

/// Text (TXT) record for arbitrary human-readable text in a DNS record.
#[allow(clippy::upper_case_acronyms)]
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct TXT(pub Vec<Vec<u8>>);

impl Resource {
    pub(crate) fn append_rdata_to_vec(&self, buf: &mut Vec<u8>) -> io::Result<()> {
        match self {
            Resource::A(address) => buf.extend_from_slice(&address.octets()),
            Resource::AAAA(address) => buf.extend_from_slice(&address.octets()),
            Resource::CNAME(name) | Resource::NS(name) | Resource::PTR(name) => {
                Message::append_qname_to_vec(buf, name)?;
            }
            Resource::TXT(txt) | Resource::SPF(txt) => txt.append_rdata_to_vec(buf)?,
            Resource::MX(mx) => mx.append_rdata_to_vec(buf)?,
            Resource::SOA(soa) => soa.append_rdata_to_vec(buf)?,
            Resource::SRV(srv) => srv.append_rdata_to_vec(buf)?,
            Resource::OPT | Resource::ANY => {
                bail!(
                    InvalidInput,
                    "resource type '{}' cannot be encoded",
                    self.r#type()
                );
            }
        }
        Ok(())
    }
}

impl Record {
    /// Appends this resource record as DNS wire-format bytes to `buf`.
    ///
    /// # Errors
    ///
    /// Returns an error if the record name, TTL, or resource data cannot be
    /// represented in DNS wire format.
    pub fn append_to_vec(&self, buf: &mut Vec<u8>) -> io::Result<()> {
        Message::append_qname_to_vec(buf, &self.name)?;
        buf.extend_from_slice(&(self.r#type() as u16).to_be_bytes());
        buf.extend_from_slice(&(self.class as u16).to_be_bytes());
        let ttl = u32::try_from(self.ttl.as_secs())
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "record TTL is too large"))?;
        buf.extend_from_slice(&ttl.to_be_bytes());

        let rdata_length_pos = buf.len();
        buf.extend_from_slice(&0_u16.to_be_bytes());
        let rdata_start = buf.len();

        self.resource.append_rdata_to_vec(buf)?;

        let rdata_length = u16::try_from(buf.len() - rdata_start)
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "record data is too long"))?;
        buf[rdata_length_pos..rdata_start].copy_from_slice(&rdata_length.to_be_bytes());
        Ok(())
    }

    pub(crate) fn parse(
        cur: &mut Cursor<&[u8]>,
        name: String,
        r#type: Type,
        class: Class,
    ) -> io::Result<Record> {
        let ttl = cur.read_u32::<BE>()?;
        let len = cur.read_u16::<BE>()?;

        // Create a new Cursor that is limited to the len field.
        //
        // cur     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10...]
        //                      ^ pos & len = 2
        //
        // record  [0, 1, 2, 3, 4, 5, 6]
        //                      ^ pos
        //
        // The record starts from zero, instead of being [4,6], this is
        // so it can jump backwards for a qname (or similar) read.

        let pos = cur.position();
        let end = pos
            .checked_add(u64::from(len))
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "record length overflow"))?;
        let end = usize::try_from(end)
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "record length is invalid"))?;
        let mut record = cur.sub_cursor(0, end)?;
        record.set_position(pos);

        // If parsing fails for this record, (and the length seems correct),
        // we could turn this into a warning instead of a full error.

        // TODO Consider changing these parse methods to some kind of common function
        // that accepts Cursor and Class.
        let resource = match r#type {
            Type::A => Resource::A(parse_a(&mut record, class)?),
            Type::AAAA => Resource::AAAA(parse_aaaa(&mut record, class)?),

            Type::NS => Resource::NS(record.read_qname()?),
            Type::SOA => Resource::SOA(SOA::parse(&mut record)?),
            Type::CNAME => Resource::CNAME(record.read_qname()?),
            Type::PTR => Resource::PTR(record.read_qname()?),
            Type::MX => Resource::MX(MX::parse(&mut record)?),
            Type::TXT => Resource::TXT(TXT::parse(&mut record)?),
            Type::SPF => Resource::SPF(TXT::parse(&mut record)?),
            Type::SRV => Resource::SRV(SRV::parse(&mut record)?),

            // This should never appear in a answer record unless we have invalid data.
            Type::Reserved | Type::OPT | Type::ANY => {
                // TODO This could be a warning, instead of a full error.
                bail!(InvalidData, "invalid record type '{}'", r#type);
            }
        };

        if record.remaining()? > 0 {
            bail!(
                Other,
                "finished '{}' parsing record with {} bytes left over",
                r#type,
                record.remaining()?
            );
        }

        // Now catch up (this is safe since record.len() < cur.len())
        cur.set_position(record.position());

        Ok(Record {
            name,
            class,
            ttl: Duration::from_secs(ttl.into()),
            resource,
        })
    }
}

/// Mail EXchanger (MX) record specifies the mail server responsible
/// for accepting email messages on behalf of a domain name.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct MX {
    /// The preference given to this RR among others at the same owner.
    /// Lower values are preferred.
    pub preference: u16,

    /// A host willing to act as a mail exchange for the owner name.
    pub exchange: String,
}

/// Start of Authority (SOA) record containing administrative information
/// about the zone. See [rfc1035].
///
/// [rfc1035]: https://datatracker.ietf.org/doc/html/rfc1035
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[allow(clippy::upper_case_acronyms)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct SOA {
    /// The name server that was the original or primary source of data for this zone.
    pub mname: String,

    /// The mailbox of the person responsible for this zone.
    ///
    /// This is stored as a valid email address, e.g "dns.admin@example.com", as opposed
    /// to the format it's typically stored in SOA records "dns\.admin.example.com". Use
    /// [`SOA::rname_to_email`] and [`SOA::email_to_rname`] to convert between the formats.
    pub rname: String,

    pub serial: u32,

    pub refresh: Duration,
    pub retry: Duration,
    pub expire: Duration,
    pub minimum: Duration,
}

/// Service (SRV) record, containg hostname and port number information of specified services. See [rfc2782].
///
/// [rfc2782]: <https://datatracker.ietf.org/doc/html/rfc2782>
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[allow(clippy::upper_case_acronyms)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct SRV {
    pub priority: u16,
    pub weight: u16,
    pub port: u16,
    pub name: String,
}

fn parse_a(cur: &mut Cursor<&[u8]>, class: Class) -> io::Result<A> {
    let mut buf = [0_u8; 4];
    cur.read_exact(&mut buf)?;

    match class {
        Class::Internet => Ok(A::new(buf[0], buf[1], buf[2], buf[3])),

        _ => bail!(InvalidData, "unsupported A record class '{}'", class),
    }
}

fn parse_aaaa(cur: &mut Cursor<&[u8]>, class: Class) -> io::Result<AAAA> {
    let mut buf = [0_u8; 16];
    cur.read_exact(&mut buf)?;

    match class {
        Class::Internet => Ok(AAAA::from(buf)),

        _ => bail!(InvalidData, "unsupported AAAA record class '{}'", class),
    }
}

impl TXT {
    fn parse(cur: &mut Cursor<&[u8]>) -> io::Result<TXT> {
        let mut txts = Vec::new();

        loop {
            // Keep reading until EOF is reached.
            let len = match cur.read_u8() {
                Ok(len) => len,
                Err(e) => match e.kind() {
                    io::ErrorKind::UnexpectedEof => break,
                    _ => return Err(e),
                },
            };

            let mut txt = vec![0; len.into()];
            cur.read_exact(&mut txt)?;
            txts.push(txt)
        }

        Ok(TXT(txts))
    }

    pub(crate) fn append_rdata_to_vec(&self, buf: &mut Vec<u8>) -> io::Result<()> {
        for value in &self.0 {
            let length = u8::try_from(value.len())
                .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "TXT value is too long"))?;
            buf.push(length);
            buf.extend_from_slice(value);
        }
        Ok(())
    }
}

impl SOA {
    pub(crate) fn parse(cur: &mut Cursor<&[u8]>) -> io::Result<SOA> {
        let mname = cur.read_qname()?;
        let rname = Self::rname_to_email(&cur.read_qname()?)
            .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;

        let serial = cur.read_u32::<BE>()?;
        let refresh = cur.read_u32::<BE>()?;
        let retry = cur.read_u32::<BE>()?;
        let expire = cur.read_u32::<BE>()?;
        let minimum = cur.read_u32::<BE>()?;

        Ok(SOA {
            mname,
            rname,

            serial,
            refresh: Duration::from_secs(refresh.into()),
            retry: Duration::from_secs(retry.into()),
            expire: Duration::from_secs(expire.into()),
            minimum: Duration::from_secs(minimum.into()),
        })
    }

    pub(crate) fn append_rdata_to_vec(&self, buf: &mut Vec<u8>) -> io::Result<()> {
        Message::append_qname_to_vec(buf, &self.mname)?;
        let rname = Self::email_to_rname(&self.rname)
            .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
        Message::append_qname_to_vec(buf, &rname)?;

        let duration_to_u32 = |duration: Duration| {
            u32::try_from(duration.as_secs()).map_err(|_| {
                io::Error::new(io::ErrorKind::InvalidData, "SOA duration is too large")
            })
        };
        for value in [
            self.serial,
            duration_to_u32(self.refresh)?,
            duration_to_u32(self.retry)?,
            duration_to_u32(self.expire)?,
            duration_to_u32(self.minimum)?,
        ] {
            buf.extend_from_slice(&value.to_be_bytes());
        }
        Ok(())
    }

    /// Converts rnames to email address, for example, "admin.example.com" is
    /// converted to "admin@example.com", per the rules in
    /// <https://datatracker.ietf.org/doc/html/rfc1035#section-8>
    pub fn rname_to_email(domain: &str) -> Result<String, ParseError> {
        // The logic is simple.
        // Find first unescaped dot and replace with a @

        // Handle the escaping. Replace the first . which isn't escapated with a \
        let mut result = String::with_capacity(domain.len());
        let mut last_char = ' ';
        let mut done = false;
        for c in domain.chars() {
            if last_char == '\\' {
                // Last character was escape, so always append this one.
                result.push(c);
            } else if c == '.' && !done {
                result.push('@');
                done = true;
            } else if c != '\\' {
                // Otherwise append if not an escape.
                result.push(c);
            }

            last_char = c;
        }

        if !done {
            return Err(ParseError::InvalidRname(domain.to_string()));
        }

        Ok(result)
    }

    pub fn email_to_rname(email: &str) -> Result<String, ParseError> {
        match email.split_once('@') {
            None => Err(ParseError::InvalidRname(email.to_string())),

            // Escape all the dots to the left of the '@',
            // replace the '@' with a '.', and leave everything after the '@' alone.
            Some((left, right)) => Ok(left.replace('.', "\\.") + "." + right),
        }
    }
}

impl MX {
    pub(crate) fn parse(cur: &mut Cursor<&[u8]>) -> io::Result<MX> {
        let preference = cur.read_u16::<BE>()?;
        let exchange = cur.read_qname()?;

        Ok(MX {
            preference,
            exchange,
        })
    }

    pub(crate) fn append_rdata_to_vec(&self, buf: &mut Vec<u8>) -> io::Result<()> {
        buf.extend_from_slice(&self.preference.to_be_bytes());
        Message::append_qname_to_vec(buf, &self.exchange)
    }
}

impl SRV {
    pub(crate) fn parse(cur: &mut Cursor<&[u8]>) -> io::Result<SRV> {
        let priority = cur.read_u16::<BE>()?;
        let weight = cur.read_u16::<BE>()?;
        let port = cur.read_u16::<BE>()?;

        let name = cur.read_qname()?;

        Ok(SRV {
            priority,
            weight,
            port,
            name,
        })
    }

    pub(crate) fn append_rdata_to_vec(&self, buf: &mut Vec<u8>) -> io::Result<()> {
        buf.extend_from_slice(&self.priority.to_be_bytes());
        buf.extend_from_slice(&self.weight.to_be_bytes());
        buf.extend_from_slice(&self.port.to_be_bytes());
        Message::append_qname_to_vec(buf, &self.name)
    }
}

impl From<&str> for TXT {
    fn from(txt: &str) -> TXT {
        TXT(vec![txt.as_bytes().to_vec()])
    }
}

impl From<&[&str]> for TXT {
    fn from(txts: &[&str]) -> TXT {
        TXT(txts.iter().map(|row| row.as_bytes().to_vec()).collect())
    }
}

#[cfg(test)]
mod tests {
    use crate::SOA;
    use pretty_assertions::assert_eq;
    use std::io::Cursor;

    static RNAME_TESTS: &[(&str, &str)] = &[
        ("username.example.com", "username@example.com"),
        ("root.localhost", "root@localhost"),
        ("Action\\.domains.ISI.EDU", "Action.domains@ISI.EDU"),
        ("a\\.b\\.c.ISI.EDU", "a.b.c@ISI.EDU"),
    ];

    #[test]
    fn test_soa_rname_to_email() {
        for (domain, email) in RNAME_TESTS {
            match SOA::rname_to_email(domain) {
                Ok(got) => assert_eq!(got, *email, "incorrect result for '{}'", domain),
                Err(err) => panic!("'{}' Failed:\n{:?}", domain, err),
            }
        }
    }

    #[test]
    fn test_soa_rname_from_email() {
        for (domain, email) in RNAME_TESTS {
            match SOA::email_to_rname(email) {
                Ok(got) => assert_eq!(got, *domain, "incorrect result for '{}'", email),
                Err(err) => panic!("'{}' Failed:\n{:?}", email, err),
            }
        }
    }

    #[test]
    fn invalid_soa_rname_returns_error() {
        let input = [
            3, b'n', b's', b'\0', // mname
            6, b'n', b'o', b't', b'a', b'n', b'\0', // invalid rname
            0, 0, 0, 1, // serial
            0, 0, 0, 1, // refresh
            0, 0, 0, 1, // retry
            0, 0, 0, 1, // expire
            0, 0, 0, 1, // minimum
        ];

        assert!(SOA::parse(&mut Cursor::new(&input)).is_err());
    }
}