domain 0.12.0

A DNS library for Rust.
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
use core::cmp::min;
use core::fmt::{Debug, Display};

use std::vec::Vec;

use octseq::builder::{EmptyBuilder, FromBuilder, OctetsBuilder, Truncate};

use crate::base::iana::Rtype;
use crate::base::name::ToName;
use crate::base::record::Record;
use crate::dnssec::sign::error::SigningError;
use crate::dnssec::sign::records::RecordsIter;
use crate::rdata::dnssec::RtypeBitmap;
use crate::rdata::{Nsec, ZoneRecordData};

//----------- GenerateNsec3Config --------------------------------------------

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GenerateNsecConfig {
    pub assume_dnskeys_will_be_added: bool,
}

impl GenerateNsecConfig {
    pub fn new() -> Self {
        Self {
            assume_dnskeys_will_be_added: true,
        }
    }

    pub fn without_assuming_dnskeys_will_be_added(mut self) -> Self {
        self.assume_dnskeys_will_be_added = false;
        self
    }
}

impl Default for GenerateNsecConfig {
    fn default() -> Self {
        Self {
            assume_dnskeys_will_be_added: true,
        }
    }
}

/// Generate DNSSEC NSEC records for an unsigned zone.
///
/// This function returns a collection of generated NSEC records for the given
/// zone, per [RFC 4034 section 4] _"The NSEC Resource Record"_, [RFC 4035
/// section 2.3] _"Including NSEC RRs in a Zone"_ and [RFC 9077] _"NSEC and
/// NSEC3: TTLs and Aggressive Use"_.
///
/// Assumes that the given records are in [`CanonicalOrd`] order and start
/// with a complete zone, i.e. including an apex SOA record. If the apex SOA
/// is not found or multiple SOA records are found at the apex error
/// [`SigningError::SoaRecordCouldNotBeDetermined`] will be returned.
///
/// Processing of records will stop at the end of the collection or at the
/// first record that lies outside the zone.
///
/// If the `assume_dnskeys_will_be_added` parameter is true the generated NSEC
/// at the apex RRset will include the `DNSKEY` record type in the NSEC type
/// bitmap.
///
/// [RFC 4034 section 4]: https://www.rfc-editor.org/rfc/rfc4034#section-4
/// [RFC 4035 section 2.3]: https://www.rfc-editor.org/rfc/rfc4035#section-2.3
/// [RFC 9077]: https://www.rfc-editor.org/rfc/rfc9077
/// [`CanonicalOrd`]: crate::base::cmp::CanonicalOrd
// TODO: Add (mutable?) iterator based variant.
#[allow(clippy::type_complexity)]
pub fn generate_nsecs<N, Octs>(
    apex_owner: &N,
    mut records: RecordsIter<'_, N, ZoneRecordData<Octs, N>>,
    config: &GenerateNsecConfig,
) -> Result<Vec<Record<N, Nsec<Octs, N>>>, SigningError>
where
    N: ToName + Clone + Display + PartialEq,
    Octs: FromBuilder,
    Octs::Builder: EmptyBuilder + Truncate + AsRef<[u8]> + AsMut<[u8]>,
    <Octs::Builder as OctetsBuilder>::AppendError: Debug,
{
    // The generated collection of NSEC RRs that will be returned to the
    // caller.
    let mut nsecs = Vec::new();

    // The CLASS to use for NSEC records. This will be determined per the rules
    // in RFC 9077 once the apex SOA RR is found.
    let mut zone_class = None;

    // The TTL to use for NSEC records. This will be determined per the rules
    // in RFC 9077 once the apex SOA RR is found.
    let mut nsec_ttl = None;

    // The owner name of a zone cut if we currently are at or below one.
    let mut cut: Option<N> = None;

    // Because of the next name thing, we need to keep the last NSEC around.
    let mut prev: Option<(N, RtypeBitmap<Octs>)> = None;

    // Skip any glue or other out-of-zone records that sort earlier than
    // the zone apex.
    records.skip_before(apex_owner);

    for owner_rrs in records {
        // If the owner is out of zone, we have moved out of our zone and are
        // done.
        if !owner_rrs.is_in_zone(apex_owner) {
            break;
        }

        // If the owner is below a zone cut, we must ignore it.
        if let Some(ref cut) = cut {
            if owner_rrs.owner().ends_with(cut) {
                continue;
            }
        }

        // A copy of the owner name. We’ll need it later.
        let name = owner_rrs.owner().clone();

        // If this owner is the parent side of a zone cut, we keep the owner
        // name for later. This also means below that if `cut.is_some()` we
        // are at the parent side of a zone.
        cut = if owner_rrs.is_zone_cut(apex_owner) {
            Some(name.clone())
        } else {
            None
        };

        if let Some((prev_name, bitmap)) = prev.take() {
            // SAFETY: nsec_ttl and zone_class will be set below before prev
            // is set to Some.
            nsecs.push(Record::new(
                prev_name.clone(),
                zone_class.unwrap(),
                nsec_ttl.unwrap(),
                Nsec::new(name.clone(), bitmap),
            ));
        }

        let mut bitmap = RtypeBitmap::<Octs>::builder();

        // RFC 4035 section 2.3:
        //   "The type bitmap of every NSEC resource record in a signed zone
        //    MUST indicate the presence of both the NSEC record itself and
        //    its corresponding RRSIG record."
        bitmap.add(Rtype::RRSIG).unwrap();

        if config.assume_dnskeys_will_be_added
            && owner_rrs.owner() == apex_owner
        {
            // Assume there's gonna be a DNSKEY.
            bitmap.add(Rtype::DNSKEY).unwrap();
        }

        bitmap.add(Rtype::NSEC).unwrap();

        for rrset in owner_rrs.rrsets() {
            // RFC 4034 section 4.1.2: (and also RFC 4035 section 2.3)
            //   "The bitmap for the NSEC RR at a delegation point requires
            //    special attention.  Bits corresponding to the delegation NS
            //    RRset and any RRsets for which the parent zone has
            //    authoritative data MUST be set; bits corresponding to any
            //    non-NS RRset for which the parent is not authoritative MUST
            //    be clear."
            if cut.is_none() || matches!(rrset.rtype(), Rtype::NS | Rtype::DS)
            {
                // RFC 4034 section 4.1.2:
                //   "Bits representing pseudo-types MUST be clear, as they do
                //    not appear in zone data."
                //
                // We don't need to do a check here as the ZoneRecordData type
                // that we require already excludes "pseudo" record types,
                // those are only included as member variants of the
                // AllRecordData type.
                bitmap.add(rrset.rtype()).unwrap()
            }

            if rrset.rtype() == Rtype::SOA {
                if rrset.len() > 1 {
                    return Err(SigningError::SoaRecordCouldNotBeDetermined);
                }

                let soa_rr = rrset.first();

                // Check that the RDATA for the SOA record can be parsed.
                let ZoneRecordData::Soa(ref soa_data) = soa_rr.data() else {
                    return Err(SigningError::SoaRecordCouldNotBeDetermined);
                };

                // RFC 9077 updated RFC 4034 (NSEC) and RFC 5155 (NSEC3) to
                // say that the "TTL of the NSEC(3) RR that is returned MUST
                // be the lesser of the MINIMUM field of the SOA record and
                // the TTL of the SOA itself".
                nsec_ttl = Some(min(soa_data.minimum(), soa_rr.ttl()));

                zone_class = Some(rrset.class());
            }
        }

        if nsec_ttl.is_none() {
            return Err(SigningError::SoaRecordCouldNotBeDetermined);
        }

        prev = Some((name, bitmap.finalize()));
    }

    if let Some((prev_name, bitmap)) = prev {
        // SAFETY: nsec_ttl and zone_class will be set above before prev
        // is set to Some.
        nsecs.push(Record::new(
            prev_name.clone(),
            zone_class.unwrap(),
            nsec_ttl.unwrap(),
            Nsec::new(apex_owner.clone(), bitmap),
        ));
    }

    Ok(nsecs)
}

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;

    use crate::base::{Name, Ttl};
    use crate::dnssec::sign::records::SortedRecords;
    use crate::dnssec::sign::test_util::*;
    use crate::zonetree::types::StoredRecordData;
    use crate::zonetree::StoredName;

    use super::*;
    use core::str::FromStr;

    type StoredSortedRecords = SortedRecords<StoredName, StoredRecordData>;

    #[test]
    fn soa_is_required() {
        let cfg = GenerateNsecConfig::default()
            .without_assuming_dnskeys_will_be_added();
        let apex = Name::from_str("a.").unwrap();
        let records = StoredSortedRecords::from_iter([mk_a_rr("some_a.a.")]);
        let res = generate_nsecs(&apex, records.owner_rrs(), &cfg);
        assert!(matches!(
            res,
            Err(SigningError::SoaRecordCouldNotBeDetermined)
        ));
    }

    #[test]
    fn multiple_soa_rrs_in_the_same_rrset_are_not_permitted() {
        let cfg = GenerateNsecConfig::default()
            .without_assuming_dnskeys_will_be_added();
        let apex = Name::from_str("a.").unwrap();
        let records = StoredSortedRecords::from_iter([
            mk_soa_rr("a.", "b.", "c."),
            mk_soa_rr("a.", "d.", "e."),
        ]);
        let res = generate_nsecs(&apex, records.owner_rrs(), &cfg);
        assert!(matches!(
            res,
            Err(SigningError::SoaRecordCouldNotBeDetermined)
        ));
    }

    #[test]
    fn records_outside_zone_are_ignored() {
        let cfg = GenerateNsecConfig::default()
            .without_assuming_dnskeys_will_be_added();
        let a_apex = Name::from_str("a.").unwrap();
        let b_apex = Name::from_str("b.").unwrap();
        let records = StoredSortedRecords::from_iter([
            mk_soa_rr("b.", "d.", "e."),
            mk_a_rr("some_a.b."),
            mk_soa_rr("a.", "b.", "c."),
            mk_a_rr("some_a.a."),
        ]);

        // Generate NSEs for the a. zone.
        let nsecs =
            generate_nsecs(&a_apex, records.owner_rrs(), &cfg).unwrap();

        assert_eq!(
            nsecs,
            [
                mk_nsec_rr("a.", "some_a.a.", "SOA RRSIG NSEC"),
                mk_nsec_rr("some_a.a.", "a.", "A RRSIG NSEC"),
            ]
        );

        // Generate NSECs for the b. zone.
        let nsecs =
            generate_nsecs(&b_apex, records.owner_rrs(), &cfg).unwrap();

        assert_eq!(
            nsecs,
            [
                mk_nsec_rr("b.", "some_a.b.", "SOA RRSIG NSEC"),
                mk_nsec_rr("some_a.b.", "b.", "A RRSIG NSEC"),
            ]
        );
    }

    #[test]
    fn glue_records_are_ignored() {
        let cfg = GenerateNsecConfig::default()
            .without_assuming_dnskeys_will_be_added();
        let apex = Name::from_str("example.").unwrap();
        let records = StoredSortedRecords::from_iter([
            mk_soa_rr("example.", "mname.", "rname."),
            mk_ns_rr("example.", "early_sorting_glue."),
            mk_ns_rr("example.", "late_sorting_glue."),
            mk_a_rr("in_zone.example."),
            mk_a_rr("early_sorting_glue."),
            mk_a_rr("late_sorting_glue."),
        ]);

        // Generate NSEs for the a. zone.
        let nsecs = generate_nsecs(&apex, records.owner_rrs(), &cfg).unwrap();

        assert_eq!(
            nsecs,
            [
                mk_nsec_rr(
                    "example.",
                    "in_zone.example.",
                    "NS SOA RRSIG NSEC"
                ),
                mk_nsec_rr("in_zone.example.", "example.", "A RRSIG NSEC"),
            ]
        );
    }

    #[test]
    fn occluded_records_are_ignored() {
        let cfg = GenerateNsecConfig::default()
            .without_assuming_dnskeys_will_be_added();
        let apex = Name::from_str("a.").unwrap();
        let records = StoredSortedRecords::from_iter([
            mk_soa_rr("a.", "b.", "c."),
            mk_ns_rr("some_ns.a.", "some_a.other.b."),
            mk_a_rr("some_a.some_ns.a."),
        ]);

        let nsecs = generate_nsecs(&apex, records.owner_rrs(), &cfg).unwrap();

        // Implicit negative test.
        assert_eq!(
            nsecs,
            [
                mk_nsec_rr("a.", "some_ns.a.", "SOA RRSIG NSEC"),
                mk_nsec_rr("some_ns.a.", "a.", "NS RRSIG NSEC"),
            ]
        );

        // Explicit negative test.
        assert!(!contains_owner(&nsecs, "some_a.some_ns.a.example."));
    }

    #[test]
    fn expect_dnskeys_at_the_apex() {
        let cfg = GenerateNsecConfig::default();

        let apex = Name::from_str("a.").unwrap();
        let records = StoredSortedRecords::from_iter([
            mk_soa_rr("a.", "b.", "c."),
            mk_a_rr("some_a.a."),
        ]);

        let nsecs = generate_nsecs(&apex, records.owner_rrs(), &cfg).unwrap();

        assert_eq!(
            nsecs,
            [
                mk_nsec_rr("a.", "some_a.a.", "SOA DNSKEY RRSIG NSEC"),
                mk_nsec_rr("some_a.a.", "a.", "A RRSIG NSEC"),
            ]
        );
    }

    #[test]
    fn rfc_4034_appendix_a_and_rfc_9077_compliant() {
        let cfg = GenerateNsecConfig::default()
            .without_assuming_dnskeys_will_be_added();

        // See https://datatracker.ietf.org/doc/html/rfc4035#appendix-A
        let zonefile = include_bytes!(
            "../../../../test-data/zonefiles/rfc4035-appendix-A.zone"
        );

        let apex = Name::from_str("example.").unwrap();
        let records = bytes_to_records(&zonefile[..]);
        let nsecs = generate_nsecs(&apex, records.owner_rrs(), &cfg).unwrap();

        assert_eq!(nsecs.len(), 10);

        assert_eq!(
            nsecs,
            [
                mk_nsec_rr("example.", "a.example.", "NS SOA MX RRSIG NSEC"),
                mk_nsec_rr("a.example.", "ai.example.", "NS DS RRSIG NSEC"),
                mk_nsec_rr(
                    "ai.example.",
                    "b.example",
                    "A HINFO AAAA RRSIG NSEC"
                ),
                mk_nsec_rr("b.example.", "ns1.example.", "NS RRSIG NSEC"),
                mk_nsec_rr("ns1.example.", "ns2.example.", "A RRSIG NSEC"),
                // The next record also validates that we comply with
                // https://datatracker.ietf.org/doc/html/rfc4034#section-6.2
                // 4.1.3. "Inclusion of Wildcard Names in NSEC RDATA" when
                // it says:
                //   "If a wildcard owner name appears in a zone, the wildcard
                //   label ("*") is treated as a literal symbol and is treated
                //   the same as any other owner name for the purposes of
                //   generating NSEC RRs. Wildcard owner names appear in the
                //   Next Domain Name field without any wildcard expansion.
                //   [RFC4035] describes the impact of wildcards on
                //   authenticated denial of existence."
                mk_nsec_rr("ns2.example.", "*.w.example.", "A RRSIG NSEC"),
                mk_nsec_rr("*.w.example.", "x.w.example.", "MX RRSIG NSEC"),
                mk_nsec_rr("x.w.example.", "x.y.w.example.", "MX RRSIG NSEC"),
                mk_nsec_rr("x.y.w.example.", "xx.example.", "MX RRSIG NSEC"),
                mk_nsec_rr(
                    "xx.example.",
                    "example.",
                    "A HINFO AAAA RRSIG NSEC"
                )
            ],
        );

        // TTLs are not compared by the eq check above so check them
        // explicitly now.
        //
        // RFC 9077 updated RFC 4034 (NSEC) and RFC 5155 (NSEC3) to say that
        // the "TTL of the NSEC(3) RR that is returned MUST be the lesser of
        // the MINIMUM field of the SOA record and the TTL of the SOA itself".
        //
        // So in our case that is min(1800, 3600) = 1800.
        for nsec in &nsecs {
            assert_eq!(nsec.ttl(), Ttl::from_secs(1800));
        }

        // https://rfc-annotations.research.icann.org/rfc4035.html#section-2.3
        // 2.3.  Including NSEC RRs in a Zone
        //   ...
        //   "The type bitmap of every NSEC resource record in a signed zone
        //   MUST indicate the presence of both the NSEC record itself and its
        //   corresponding RRSIG record."
        for nsec in &nsecs {
            assert!(nsec.data().types().contains(Rtype::NSEC));
            assert!(nsec.data().types().contains(Rtype::RRSIG));
        }

        // https://rfc-annotations.research.icann.org/rfc4034.html#section-4.1.1
        // 4.1.2.  The Type Bit Maps Field
        //   "Bits representing pseudo-types MUST be clear, as they do not
        //    appear in zone data."
        //
        // There is nothing to test for this as it is excluded at the Rust
        // type system level by the generate_nsecs() function taking
        // ZoneRecordData (which excludes pseudo record types) as input rather
        // than AllRecordData (which includes pseudo record types).

        // https://rfc-annotations.research.icann.org/rfc4034.html#section-4.1.1
        // 4.1.2.  The Type Bit Maps Field
        //   ...
        //   "A zone MUST NOT include an NSEC RR for any domain name that only
        //    holds glue records."
        //
        // The "rfc4035-appendix-A.zone" file that we load contains glue A
        // records for ns1.example, ns1.a.example, ns1.b.example, ns2.example
        // and ns2.a.example all with no other record types at that name. We
        // can verify that an NSEC RR was NOT created for those that are not
        // within the example zone as we are not authoritative for thos.
        assert!(contains_owner(&nsecs, "ns1.example."));
        assert!(!contains_owner(&nsecs, "ns1.a.example."));
        assert!(!contains_owner(&nsecs, "ns1.b.example."));
        assert!(contains_owner(&nsecs, "ns2.example."));
        assert!(!contains_owner(&nsecs, "ns2.a.example."));

        // https://rfc-annotations.research.icann.org/rfc4035.html#section-2.3
        // 2.3.  Including NSEC RRs in a Zone
        //   ...
        //  "The bitmap for the NSEC RR at a delegation point requires special
        //  attention.  Bits corresponding to the delegation NS RRset and any
        //  RRsets for which the parent zone has authoritative data MUST be
        //  set; bits corresponding to any non-NS RRset for which the parent
        //  is not authoritative MUST be clear."
        //
        // The "rfc4035-appendix-A.zone" file that we load has been modified
        // compared to the original to include a glue A record at b.example.
        // We can verify that an NSEC RR was NOT created for that name.
        let name = mk_name("b.example.");
        let nsec = nsecs.iter().find(|rr| rr.owner() == &name).unwrap();
        assert!(nsec.data().types().contains(Rtype::NSEC));
        assert!(nsec.data().types().contains(Rtype::RRSIG));
        assert!(!nsec.data().types().contains(Rtype::A));
    }

    #[test]
    fn existing_nsec_records_are_ignored() {
        let cfg = GenerateNsecConfig::default();

        let apex = Name::from_str("a.").unwrap();
        let records = StoredSortedRecords::from_iter([
            mk_soa_rr("a.", "b.", "c."),
            mk_a_rr("some_a.a."),
            mk_nsec_rr("a.", "some_a.a.", "SOA NSEC"),
            mk_nsec_rr("some_a.a.", "a.", "A RRSIG NSEC"),
        ]);

        let nsecs = generate_nsecs(&apex, records.owner_rrs(), &cfg).unwrap();

        assert_eq!(
            nsecs,
            [
                mk_nsec_rr("a.", "some_a.a.", "SOA DNSKEY RRSIG NSEC"),
                mk_nsec_rr("some_a.a.", "a.", "A RRSIG NSEC"),
            ]
        );
    }
}