dns_types/protocol/
deserialise.rs

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
//! Deserialisation of DNS messages from the network.  See the `types`
//!
//! module for details of the format.

use bytes::Bytes;
use std::net::{Ipv4Addr, Ipv6Addr};

use crate::protocol::types::*;

impl Message {
    /// # Errors
    ///
    /// If the message cannot be parsed.
    pub fn from_octets(octets: &[u8]) -> Result<Self, Error> {
        Self::deserialise(&mut ConsumableBuffer::new(octets))
    }

    /// # Errors
    ///
    /// If the message cannot be parsed.
    fn deserialise(buffer: &mut ConsumableBuffer) -> Result<Self, Error> {
        let header = Header::deserialise(buffer)?;
        let qdcount = buffer.next_u16().ok_or(Error::HeaderTooShort(header.id))?;
        let ancount = buffer.next_u16().ok_or(Error::HeaderTooShort(header.id))?;
        let nscount = buffer.next_u16().ok_or(Error::HeaderTooShort(header.id))?;
        let arcount = buffer.next_u16().ok_or(Error::HeaderTooShort(header.id))?;

        let mut questions = Vec::with_capacity(qdcount.into());
        let mut answers = Vec::with_capacity(ancount.into());
        let mut authority = Vec::with_capacity(nscount.into());
        let mut additional = Vec::with_capacity(arcount.into());

        for _ in 0..qdcount {
            questions.push(Question::deserialise(header.id, buffer)?);
        }
        for _ in 0..ancount {
            answers.push(ResourceRecord::deserialise(header.id, buffer)?);
        }
        for _ in 0..nscount {
            authority.push(ResourceRecord::deserialise(header.id, buffer)?);
        }
        for _ in 0..arcount {
            additional.push(ResourceRecord::deserialise(header.id, buffer)?);
        }

        Ok(Self {
            header,
            questions,
            answers,
            authority,
            additional,
        })
    }
}

impl Header {
    /// # Errors
    ///
    /// If the header is too short.
    fn deserialise(buffer: &mut ConsumableBuffer) -> Result<Self, Error> {
        let id = buffer.next_u16().ok_or(Error::CompletelyBusted)?;
        let flags1 = buffer.next_u8().ok_or(Error::HeaderTooShort(id))?;
        let flags2 = buffer.next_u8().ok_or(Error::HeaderTooShort(id))?;

        Ok(Self {
            id,
            is_response: flags1 & HEADER_MASK_QR != 0,
            opcode: Opcode::from((flags1 & HEADER_MASK_OPCODE) >> HEADER_OFFSET_OPCODE),
            is_authoritative: flags1 & HEADER_MASK_AA != 0,
            is_truncated: flags1 & HEADER_MASK_TC != 0,
            recursion_desired: flags1 & HEADER_MASK_RD != 0,
            recursion_available: flags2 & HEADER_MASK_RA != 0,
            rcode: Rcode::from((flags2 & HEADER_MASK_RCODE) >> HEADER_OFFSET_RCODE),
        })
    }
}

impl Question {
    /// # Errors
    ///
    /// If the question cannot be parsed.
    fn deserialise(id: u16, buffer: &mut ConsumableBuffer) -> Result<Self, Error> {
        let name = DomainName::deserialise(id, buffer)?;
        let qtype = QueryType::deserialise(id, buffer)?;
        let qclass = QueryClass::deserialise(id, buffer)?;

        Ok(Self {
            name,
            qtype,
            qclass,
        })
    }
}

impl ResourceRecord {
    /// # Errors
    ///
    /// If the record cannot be parsed.
    fn deserialise(id: u16, buffer: &mut ConsumableBuffer) -> Result<Self, Error> {
        let name = DomainName::deserialise(id, buffer)?;
        let rtype = RecordType::deserialise(id, buffer)?;
        let rclass = RecordClass::deserialise(id, buffer)?;
        let ttl = buffer.next_u32().ok_or(Error::ResourceRecordTooShort(id))?;
        let rdlength = buffer.next_u16().ok_or(Error::ResourceRecordTooShort(id))?;

        let rdata_start = buffer.position;

        let mut raw_rdata = || {
            if let Some(octets) = buffer.take(rdlength as usize) {
                Ok(Bytes::copy_from_slice(octets))
            } else {
                Err(Error::ResourceRecordTooShort(id))
            }
        };

        // for records which include domain names, deserialise them to
        // expand pointers.
        let rtype_with_data = match rtype {
            RecordType::A => RecordTypeWithData::A {
                address: Ipv4Addr::from(
                    buffer.next_u32().ok_or(Error::ResourceRecordTooShort(id))?,
                ),
            },
            RecordType::NS => RecordTypeWithData::NS {
                nsdname: DomainName::deserialise(id, buffer)?,
            },
            RecordType::MD => RecordTypeWithData::MD {
                madname: DomainName::deserialise(id, buffer)?,
            },
            RecordType::MF => RecordTypeWithData::MF {
                madname: DomainName::deserialise(id, buffer)?,
            },
            RecordType::CNAME => RecordTypeWithData::CNAME {
                cname: DomainName::deserialise(id, buffer)?,
            },
            RecordType::SOA => RecordTypeWithData::SOA {
                mname: DomainName::deserialise(id, buffer)?,
                rname: DomainName::deserialise(id, buffer)?,
                serial: buffer.next_u32().ok_or(Error::ResourceRecordTooShort(id))?,
                refresh: buffer.next_u32().ok_or(Error::ResourceRecordTooShort(id))?,
                retry: buffer.next_u32().ok_or(Error::ResourceRecordTooShort(id))?,
                expire: buffer.next_u32().ok_or(Error::ResourceRecordTooShort(id))?,
                minimum: buffer.next_u32().ok_or(Error::ResourceRecordTooShort(id))?,
            },
            RecordType::MB => RecordTypeWithData::MB {
                madname: DomainName::deserialise(id, buffer)?,
            },
            RecordType::MG => RecordTypeWithData::MG {
                mdmname: DomainName::deserialise(id, buffer)?,
            },
            RecordType::MR => RecordTypeWithData::MR {
                newname: DomainName::deserialise(id, buffer)?,
            },
            RecordType::NULL => RecordTypeWithData::NULL {
                octets: raw_rdata()?,
            },
            RecordType::WKS => RecordTypeWithData::WKS {
                octets: raw_rdata()?,
            },
            RecordType::PTR => RecordTypeWithData::PTR {
                ptrdname: DomainName::deserialise(id, buffer)?,
            },
            RecordType::HINFO => RecordTypeWithData::HINFO {
                octets: raw_rdata()?,
            },
            RecordType::MINFO => RecordTypeWithData::MINFO {
                rmailbx: DomainName::deserialise(id, buffer)?,
                emailbx: DomainName::deserialise(id, buffer)?,
            },
            RecordType::MX => RecordTypeWithData::MX {
                preference: buffer.next_u16().ok_or(Error::ResourceRecordTooShort(id))?,
                exchange: DomainName::deserialise(id, buffer)?,
            },
            RecordType::TXT => RecordTypeWithData::TXT {
                octets: raw_rdata()?,
            },
            RecordType::AAAA => RecordTypeWithData::AAAA {
                address: Ipv6Addr::new(
                    buffer.next_u16().ok_or(Error::ResourceRecordTooShort(id))?,
                    buffer.next_u16().ok_or(Error::ResourceRecordTooShort(id))?,
                    buffer.next_u16().ok_or(Error::ResourceRecordTooShort(id))?,
                    buffer.next_u16().ok_or(Error::ResourceRecordTooShort(id))?,
                    buffer.next_u16().ok_or(Error::ResourceRecordTooShort(id))?,
                    buffer.next_u16().ok_or(Error::ResourceRecordTooShort(id))?,
                    buffer.next_u16().ok_or(Error::ResourceRecordTooShort(id))?,
                    buffer.next_u16().ok_or(Error::ResourceRecordTooShort(id))?,
                ),
            },
            RecordType::SRV => RecordTypeWithData::SRV {
                priority: buffer.next_u16().ok_or(Error::ResourceRecordTooShort(id))?,
                weight: buffer.next_u16().ok_or(Error::ResourceRecordTooShort(id))?,
                port: buffer.next_u16().ok_or(Error::ResourceRecordTooShort(id))?,
                target: DomainName::deserialise(id, buffer)?,
            },
            RecordType::Unknown(tag) => RecordTypeWithData::Unknown {
                tag,
                octets: raw_rdata()?,
            },
        };

        let rdata_stop = buffer.position;

        if rdata_stop == rdata_start + (rdlength as usize) {
            Ok(Self {
                name,
                rtype_with_data,
                rclass,
                ttl,
            })
        } else {
            Err(Error::ResourceRecordInvalid(id))
        }
    }
}

impl DomainName {
    /// # Errors
    ///
    /// If the domain cannot be parsed.
    #[allow(clippy::missing_panics_doc)]
    fn deserialise(id: u16, buffer: &mut ConsumableBuffer) -> Result<Self, Error> {
        let mut len = 0;
        let mut labels = Vec::<Label>::with_capacity(5);
        let start = buffer.position;

        'outer: loop {
            let size = buffer.next_u8().ok_or(Error::DomainTooShort(id))?;

            if usize::from(size) <= LABEL_MAX_LEN {
                len += 1;

                if size == 0 {
                    labels.push(Label::new());
                    break 'outer;
                }

                if let Some(os) = buffer.take(size as usize) {
                    // safe because of the bounds check above
                    let label = Label::try_from(os).unwrap();
                    len += label.len() as usize;
                    labels.push(label);
                } else {
                    return Err(Error::DomainTooShort(id));
                }

                if len > DOMAINNAME_MAX_LEN {
                    break 'outer;
                }
            } else if size >= 192 {
                // this requires re-parsing the pointed-to domain -
                // not great but works for now.
                let hi = size & 0b0011_1111;
                let lo = buffer.next_u8().ok_or(Error::DomainTooShort(id))?;
                let ptr = u16::from_be_bytes([hi, lo]).into();

                // pointer must be to an earlier record (not merely a
                // different one: an earlier one: RFC 1035 section
                // 4.1.4)
                if ptr >= start {
                    return Err(Error::DomainPointerInvalid(id));
                }

                let mut other = DomainName::deserialise(id, &mut buffer.at_offset(ptr))?;
                len += other.len;
                labels.append(&mut other.labels);
                break 'outer;
            } else {
                return Err(Error::DomainLabelInvalid(id));
            }
        }

        if len <= DOMAINNAME_MAX_LEN {
            Ok(DomainName { labels, len })
        } else {
            Err(Error::DomainTooLong(id))
        }
    }
}

impl QueryType {
    /// # Errors
    ///
    /// If the query type is too short.
    fn deserialise(id: u16, buffer: &mut ConsumableBuffer) -> Result<Self, Error> {
        let value = buffer.next_u16().ok_or(Error::QuestionTooShort(id))?;
        Ok(Self::from(value))
    }
}

impl QueryClass {
    /// # Errors
    ///
    /// If the query class is too short.
    fn deserialise(id: u16, buffer: &mut ConsumableBuffer) -> Result<Self, Error> {
        let value = buffer.next_u16().ok_or(Error::QuestionTooShort(id))?;
        Ok(Self::from(value))
    }
}

impl RecordType {
    /// # Errors
    ///
    /// If the record type is too short.
    fn deserialise(id: u16, buffer: &mut ConsumableBuffer) -> Result<Self, Error> {
        let value = buffer.next_u16().ok_or(Error::ResourceRecordTooShort(id))?;
        Ok(Self::from(value))
    }
}

impl RecordClass {
    /// # Errors
    ///
    /// If the record class is too short.
    fn deserialise(id: u16, buffer: &mut ConsumableBuffer) -> Result<Self, Error> {
        let value = buffer.next_u16().ok_or(Error::ResourceRecordTooShort(id))?;
        Ok(Self::from(value))
    }
}

/// Errors encountered when parsing a datagram.  In all the errors
/// which have a `u16` parameter, that is the ID from the header - so
/// that an error response can be sent.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Error {
    /// The datagram is not even 2 octets long, so it doesn't even
    /// contain a valid ID.  An error cannot even be sent back to the
    /// client in this case as, without an ID, it cannot be linked
    /// with the correct query.
    CompletelyBusted,

    /// The header is missing one or more required fields.
    HeaderTooShort(u16),

    /// A question ends with an incomplete field.
    QuestionTooShort(u16),

    /// A resource record ends with an incomplete field.
    ResourceRecordTooShort(u16),

    /// A resource record is the wrong format.
    ResourceRecordInvalid(u16),

    /// A domain is incomplete.
    DomainTooShort(u16),

    /// A domain is over 255 octets in size.
    DomainTooLong(u16),

    /// A domain pointer points to or after the current record.
    DomainPointerInvalid(u16),

    /// A domain label is longer than 63 octets, but not a pointer.
    DomainLabelInvalid(u16),
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Error::CompletelyBusted | Error::HeaderTooShort(_) => write!(f, "header too short"),
            Error::QuestionTooShort(_) => write!(f, "question too short"),
            Error::ResourceRecordTooShort(_) => write!(f, "resource record too short"),
            Error::ResourceRecordInvalid(_) => write!(
                f,
                "resource record RDLENGTH field does not match parsed RDATA length"
            ),
            Error::DomainTooShort(_) => write!(f, "domain name too short"),
            Error::DomainTooLong(_) => write!(f, "domain name too long"),
            Error::DomainPointerInvalid(_) => write!(f, "domain name compression pointer invalid"),
            Error::DomainLabelInvalid(_) => write!(f, "domain label invalid"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}

impl Error {
    pub fn id(self) -> Option<u16> {
        match self {
            Error::CompletelyBusted => None,
            Error::HeaderTooShort(id) => Some(id),
            Error::QuestionTooShort(id) => Some(id),
            Error::ResourceRecordTooShort(id) => Some(id),
            Error::ResourceRecordInvalid(id) => Some(id),
            Error::DomainTooShort(id) => Some(id),
            Error::DomainTooLong(id) => Some(id),
            Error::DomainPointerInvalid(id) => Some(id),
            Error::DomainLabelInvalid(id) => Some(id),
        }
    }
}

/// A buffer which will be consumed by the parsing process.
struct ConsumableBuffer<'a> {
    octets: &'a [u8],
    position: usize,
}

impl<'a> ConsumableBuffer<'a> {
    fn new(octets: &'a [u8]) -> Self {
        Self {
            octets,
            position: 0,
        }
    }

    fn next_u8(&mut self) -> Option<u8> {
        if self.octets.len() > self.position {
            let a = self.octets[self.position];
            self.position += 1;
            Some(a)
        } else {
            None
        }
    }

    fn next_u16(&mut self) -> Option<u16> {
        if self.octets.len() > self.position + 1 {
            let a = self.octets[self.position];
            let b = self.octets[self.position + 1];
            self.position += 2;
            Some(u16::from_be_bytes([a, b]))
        } else {
            None
        }
    }

    fn next_u32(&mut self) -> Option<u32> {
        if self.octets.len() > self.position + 3 {
            let a = self.octets[self.position];
            let b = self.octets[self.position + 1];
            let c = self.octets[self.position + 2];
            let d = self.octets[self.position + 3];
            self.position += 4;
            Some(u32::from_be_bytes([a, b, c, d]))
        } else {
            None
        }
    }

    fn take(&mut self, size: usize) -> Option<&'a [u8]> {
        if self.octets.len() >= self.position + size {
            let slice = &self.octets[self.position..self.position + size];
            self.position += size;
            Some(slice)
        } else {
            None
        }
    }

    fn at_offset(&self, position: usize) -> ConsumableBuffer<'a> {
        Self {
            octets: self.octets,
            position,
        }
    }
}