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
//! Signing related traits.
//!
//! This module provides traits which can be used to simplify invocation of
//! [`crate::dnssec::sign::sign_zone()`] for [`Record`] collection types.
use core::convert::From;
use core::fmt::{Debug, Display};
use core::iter::Extend;
use core::marker::Send;
use core::ops::Deref;

use std::boxed::Box;
use std::hash::Hash;
use std::vec::Vec;

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

use crate::base::cmp::CanonicalOrd;
use crate::base::name::ToName;
use crate::base::record::Record;
use crate::base::Name;
use crate::crypto::sign::SignRaw;
use crate::dnssec::sign::error::SigningError;
use crate::dnssec::sign::keys::SigningKey;
use crate::dnssec::sign::records::{
    DefaultSorter, RecordsIter, Rrset, SortedRecords, Sorter,
};
use crate::dnssec::sign::sign_zone;
use crate::dnssec::sign::signatures::rrsigs::sign_sorted_zone_records;
use crate::dnssec::sign::signatures::rrsigs::GenerateRrsigConfig;
use crate::dnssec::sign::SignableZoneInOut;
use crate::dnssec::sign::SigningConfig;
use crate::rdata::dnssec::Timestamp;
use crate::rdata::{Rrsig, ZoneRecordData};

//------------ SortedExtend --------------------------------------------------

pub trait SortedExtend<N, Octs, Sort>
where
    Sort: Sorter,
{
    fn sorted_extend<
        T: IntoIterator<Item = Record<N, ZoneRecordData<Octs, N>>>,
    >(
        &mut self,
        iter: T,
    );
}

impl<N, Octs, Sort> SortedExtend<N, Octs, Sort>
    for SortedRecords<N, ZoneRecordData<Octs, N>, Sort>
where
    N: Send + PartialEq + ToName,
    Octs: Send,
    Sort: Sorter,
    ZoneRecordData<Octs, N>: CanonicalOrd + PartialEq,
{
    fn sorted_extend<
        T: IntoIterator<Item = Record<N, ZoneRecordData<Octs, N>>>,
    >(
        &mut self,
        iter: T,
    ) {
        // SortedRecords::extend() takes care of sorting and de-duplication so
        // we don't have to.
        self.extend(iter);
    }
}

//---- impl for Vec

impl<N, Octs, Sort> SortedExtend<N, Octs, Sort>
    for Vec<Record<N, ZoneRecordData<Octs, N>>>
where
    N: Send + PartialEq + ToName,
    Octs: Send,
    Sort: Sorter,
    ZoneRecordData<Octs, N>: CanonicalOrd + PartialEq,
{
    fn sorted_extend<
        T: IntoIterator<Item = Record<N, ZoneRecordData<Octs, N>>>,
    >(
        &mut self,
        iter: T,
    ) {
        // This call to extend may add duplicates.
        self.extend(iter);

        // Sort the records using the provided sort implementation.
        Sort::sort_by(self, CanonicalOrd::canonical_cmp);

        // And remove any duplicates that were created.
        // Requires that the vector first be sorted.
        self.dedup();
    }
}

//------------ SignableZone --------------------------------------------------

/// DNSSEC sign an unsigned zone using the given configuration and keys.
///
/// Types that implement this trait can be signed using the trait provided
/// [`sign_zone()`] function which will insert the generated records in order
/// (assuming that it correctly implements [`SortedExtend`]) into the given
/// `out` record collection.
///
/// # Example
///
/// ```
/// # use domain::base::{Name, Record, Serial, Ttl};
/// # use domain::base::iana::Class;
/// # use domain::crypto::common;
/// # use domain::crypto::sign::{generate, GenerateParams, KeyPair};
/// # use domain::dnssec::sign::keys::SigningKey;
/// # let (sec_bytes, pub_bytes) = generate(&GenerateParams::Ed25519,
/// #      256).unwrap();
/// # let key_pair = KeyPair::from_bytes(&sec_bytes, &pub_bytes).unwrap();
/// # let root = Name::<Vec<u8>>::root();
/// # let key = SigningKey::new(root.clone(), 257, key_pair);
/// use domain::rdata::{rfc1035::Soa, ZoneRecordData};
/// use domain::rdata::dnssec::Timestamp;
/// use domain::dnssec::sign::records::SortedRecords;
/// use domain::dnssec::sign::traits::SignableZone;
/// use domain::dnssec::sign::SigningConfig;
///
/// // Create a sorted collection of records.
/// //
/// // Note: You can also use a plain Vec here (or any other type that is
/// // compatible with the SignableZone or SignableZoneInPlace trait bounds)
/// // but then you are responsible for ensuring that records in the zone are
/// // in DNSSEC compatible order, e.g. by calling
/// // `sort_by(CanonicalOrd::canonical_cmp)` before calling `sign_zone()`.
/// let mut records = SortedRecords::default();
///
/// // Insert records into the collection. Just a dummy SOA for this example.
/// let soa = ZoneRecordData::Soa(Soa::new(
///     root.clone(),
///     root.clone(),
///     Serial::now(),
///     Ttl::ZERO,
///     Ttl::ZERO,
///     Ttl::ZERO,
///     Ttl::ZERO));
/// records.insert(Record::new(root.clone(), Class::IN, Ttl::ZERO, soa)).unwrap();
///
/// // Generate or import signing keys (see above).
///
/// // Assign signature validity period and operator intent to the keys.
/// let keys = [&key];
///
/// // Create a signing configuration.
/// let signing_config = SigningConfig::new(Default::default(), 0.into(), 0.into());
///
/// // Then generate the records which when added to the zone make it signed.
/// let mut signer_generated_records = SortedRecords::default();
///
/// records.sign_zone(
///     &root,
///     &signing_config,
///     &keys,
///     &mut signer_generated_records).unwrap();
/// ```
///
/// [`sign_zone()`]: SignableZone::sign_zone
pub trait SignableZone<N, Octs, Sort>:
    Deref<Target = [Record<N, ZoneRecordData<Octs, N>>]>
where
    N: Clone + Debug + ToName + From<Name<Octs>> + PartialEq + Ord + Hash,
    Octs: Clone
        + Debug
        + FromBuilder
        + From<&'static [u8]>
        + Send
        + OctetsFrom<Vec<u8>>
        + From<Box<[u8]>>
        + Default,
    <Octs as FromBuilder>::Builder: EmptyBuilder + AsRef<[u8]> + AsMut<[u8]>,
    Sort: Sorter,
{
    // TODO
    // fn iter_mut<T>(&mut self) -> T;

    /// DNSSEC sign an unsigned zone using the given configuration and keys.
    ///
    /// This function is a convenience wrapper around calling
    /// [`crate::dnssec::sign::sign_zone()`] function with enum variant
    /// [`SignableZoneInOut::SignInto`].
    fn sign_zone<Inner, T>(
        &self,
        apex_owner: &N,
        signing_config: &SigningConfig<Octs, Sort>,
        signing_keys: &[&SigningKey<Octs, Inner>],
        out: &mut T,
    ) -> Result<(), SigningError>
    where
        Inner: Debug + SignRaw,
        N: Display + Send + CanonicalOrd,
        <Octs as FromBuilder>::Builder: Truncate,
        <<Octs as FromBuilder>::Builder as OctetsBuilder>::AppendError: Debug,
        T: Deref<Target = [Record<N, ZoneRecordData<Octs, N>>]>
            + SortedExtend<N, Octs, Sort>
            + ?Sized,
        Self: Sized,
    {
        let in_out = SignableZoneInOut::new_into(self, out);
        sign_zone::<N, Octs, _, Inner, Sort, T>(
            apex_owner,
            in_out,
            signing_config,
            signing_keys,
        )
    }
}

/// DNSSEC sign an unsigned zone using the given configuration and keys.
///
/// Implemented for any type that dereferences to `[Record<N,
/// ZoneRecordData<Octs, N>>]`.
impl<N, Octs, Sort, T> SignableZone<N, Octs, Sort> for T
where
    N: Clone
        + Debug
        + ToName
        + From<Name<Octs>>
        + PartialEq
        + Send
        + CanonicalOrd
        + Ord
        + Hash,
    Octs: Clone
        + Debug
        + FromBuilder
        + From<&'static [u8]>
        + Send
        + OctetsFrom<Vec<u8>>
        + From<Box<[u8]>>
        + Default,
    <Octs as FromBuilder>::Builder: EmptyBuilder + AsRef<[u8]> + AsMut<[u8]>,
    Sort: Sorter,
    T: Deref<Target = [Record<N, ZoneRecordData<Octs, N>>]>,
{
}

//------------ SignableZoneInPlace -------------------------------------------

/// DNSSEC sign an unsigned zone in-place using the given configuration and
/// keys.
///
/// Types that implement this trait can be signed using the trait provided
/// [`sign_zone()`] function which will insert the generated records in order
/// (assuming that it correctly implements [`SortedExtend`]) into the
/// collection being signed.
///
/// # Example
///
/// ```
/// # use domain::base::{Name, Record, Serial, Ttl};
/// # use domain::base::iana::Class;
/// # use domain::crypto::common;
/// # use domain::crypto::sign::{generate, GenerateParams, KeyPair};
/// # use domain::dnssec::sign::keys::SigningKey;
/// # let (sec_bytes, pub_bytes) = generate(
/// #      &GenerateParams::Ed25519,
/// #      256).unwrap();
/// # let key_pair = KeyPair::from_bytes(&sec_bytes, &pub_bytes).unwrap();
/// # let root = Name::<Vec<u8>>::root();
/// # let key = SigningKey::new(root.clone(), 257, key_pair);
/// use domain::rdata::{rfc1035::Soa, ZoneRecordData};
/// use domain::rdata::dnssec::Timestamp;
/// use domain::dnssec::sign::records::SortedRecords;
/// use domain::dnssec::sign::traits::SignableZoneInPlace;
/// use domain::dnssec::sign::SigningConfig;
/// use domain::dnssec::sign::records::DefaultSorter;
///
/// // Create a sorted collection of records.
/// //
/// // Note: You can also use a plain Vec here (or any other type that is
/// // compatible with the SignableZone or SignableZoneInPlace trait bounds)
/// // but then you are responsible for ensuring that records in the zone are
/// // in DNSSEC compatible order, e.g. by calling
/// // `sort_by(CanonicalOrd::canonical_cmp)` before calling `sign_zone()`.
/// let mut records = SortedRecords::default();
///
/// // Insert records into the collection. Just a dummy SOA for this example.
/// let soa = ZoneRecordData::<Vec<u8>, _>::Soa(Soa::new(
///     root.clone(),
///     root.clone(),
///     Serial::now(),
///     Ttl::ZERO,
///     Ttl::ZERO,
///     Ttl::ZERO,
///     Ttl::ZERO));
/// records.insert(Record::new(root.clone(), Class::IN, Ttl::ZERO, soa)).unwrap();
///
/// // Generate or import signing keys (see above).
///
/// // Assign signature validity period and operator intent to the keys.
/// let keys = [&key];
///
/// // Create a signing configuration.
/// let signing_config: SigningConfig<Vec<u8>, DefaultSorter> =
///     SigningConfig::new(Default::default(), 0.into(), 0.into());
///
/// // Then sign the zone in-place.
/// records.sign_zone(&root, &signing_config, &keys).unwrap();
/// ```
///
/// [`sign_zone()`]: SignableZoneInPlace::sign_zone
pub trait SignableZoneInPlace<N, Octs, Sort>:
    SignableZone<N, Octs, Sort> + SortedExtend<N, Octs, Sort>
where
    N: Clone + Debug + ToName + From<Name<Octs>> + PartialEq + Ord + Hash,
    Octs: Clone
        + Debug
        + FromBuilder
        + From<&'static [u8]>
        + Send
        + OctetsFrom<Vec<u8>>
        + From<Box<[u8]>>
        + Default,
    <Octs as FromBuilder>::Builder: EmptyBuilder + AsRef<[u8]> + AsMut<[u8]>,
    Self: SortedExtend<N, Octs, Sort> + Sized,
    Sort: Sorter,
{
    /// DNSSEC sign an unsigned zone in-place using the given configuration
    /// and keys.
    ///
    /// This function is a convenience wrapper around calling
    /// [`crate::dnssec::sign::sign_zone()`] function with enum variant
    /// [`SignableZoneInOut::SignInPlace`].
    fn sign_zone<Inner>(
        &mut self,
        apex_owner: &N,
        signing_config: &SigningConfig<Octs, Sort>,
        signing_keys: &[&SigningKey<Octs, Inner>],
    ) -> Result<(), SigningError>
    where
        Inner: Debug + SignRaw,
        N: Display + Send + CanonicalOrd,
        <Octs as FromBuilder>::Builder: Truncate,
        <<Octs as FromBuilder>::Builder as OctetsBuilder>::AppendError: Debug,
    {
        let in_out =
            SignableZoneInOut::<_, _, Self, _, _>::new_in_place(self);
        sign_zone::<N, Octs, _, Inner, Sort, _>(
            apex_owner,
            in_out,
            signing_config,
            signing_keys,
        )
    }
}

//--- impl SignableZoneInPlace for SortedRecords

/// DNSSEC sign an unsigned zone in-place using the given configuration and
/// keys.
///
/// Implemented for any type that dereferences to `[Record<N,
/// ZoneRecordData<Octs, N>>]` and which implements the [`SortedExtend`]
/// trait.
impl<N, Octs, Sort, T> SignableZoneInPlace<N, Octs, Sort> for T
where
    N: Clone
        + Debug
        + ToName
        + From<Name<Octs>>
        + PartialEq
        + Send
        + CanonicalOrd
        + Hash
        + Ord,
    Octs: Clone
        + Debug
        + FromBuilder
        + From<&'static [u8]>
        + Send
        + OctetsFrom<Vec<u8>>
        + From<Box<[u8]>>
        + Default,
    <Octs as FromBuilder>::Builder: EmptyBuilder + AsRef<[u8]> + AsMut<[u8]>,
    Sort: Sorter,
    T: Deref<Target = [Record<N, ZoneRecordData<Octs, N>>]>,
    T: SortedExtend<N, Octs, Sort> + Sized,
{
}

//------------ Signable ------------------------------------------------------

/// A trait for generating DNSSEC signatures for one or more [`Record`]s.
///
/// Unlike [`SignableZone`] this trait is intended to be implemented by types
/// that represent one or more [`Record`]s that together do **NOT** constitute
/// a full DNS zone, specifically collections that lack the zone apex records.
///
/// Functions offered by this trait will **only** generate `RRSIG` records.
/// Other DNSSEC record types such as `NSEC(3)` and `DNSKEY` can only be
/// generated in the context of a full zone and so will **NOT** be generated
/// by the functions offered by this trait.
///
/// # Example
///
/// ```
/// # use domain::base::{Name, Record, Ttl};
/// # use domain::base::iana::Class;
/// # use domain::crypto::common;
/// # use domain::crypto::sign::{generate, GenerateParams, KeyPair};
/// # use domain::dnssec::sign::keys::{SigningKey};
/// # use domain::dnssec::sign::records::{Rrset, SortedRecords};
/// # use domain::rdata::{A, ZoneRecordData};
/// # use domain::zonetree::StoredName;
/// # use std::str::FromStr;
/// # let (sec_bytes, pub_bytes) = generate(
/// #      &GenerateParams::Ed25519,
/// #      256).unwrap();
/// # let key_pair = KeyPair::from_bytes(&sec_bytes, &pub_bytes).unwrap();
/// # let root = Name::<Vec<u8>>::root();
/// # let key = SigningKey::new(root, 257, key_pair);
/// # let keys = [&key];
/// # let mut records = SortedRecords::default();
/// # records.insert(Record::new(Name::from_str("www.example.com.")
///       .unwrap(), Class::IN, Ttl::from_secs(3600),
///       ZoneRecordData::A(A::from_str("1.2.3.4").unwrap()))).unwrap();
/// use domain::dnssec::sign::traits::Signable;
/// let apex = Name::<Vec<u8>>::root();
/// let rrset = Rrset::new_from_owned(&records).expect("records is not empty");
/// let generated_records = rrset.sign(&apex, &keys, 0.into(), 0.into()).unwrap();
/// ```
pub trait Signable<N, Octs, Inner, Sort = DefaultSorter>
where
    N: ToName
        + CanonicalOrd
        + Send
        + Debug
        + Display
        + Clone
        + PartialEq
        + From<Name<Octs>>,
    Inner: Debug + SignRaw,
    Octs: From<Box<[u8]>>
        + From<&'static [u8]>
        + FromBuilder
        + Clone
        + Debug
        + OctetsFrom<std::vec::Vec<u8>>
        + Send,
    <Octs as FromBuilder>::Builder: EmptyBuilder + AsRef<[u8]> + AsMut<[u8]>,
    Sort: Sorter,
{
    fn owner_rrs(&self) -> RecordsIter<'_, N, ZoneRecordData<Octs, N>>;

    /// Generate `RRSIG` records for this type.
    ///
    /// This function is a thin wrapper around [`sign_sorted_zone_records()`].
    #[allow(clippy::type_complexity)]
    fn sign(
        &self,
        apex_owner: &N,
        keys: &[&SigningKey<Octs, Inner>],
        inception: Timestamp,
        expiration: Timestamp,
    ) -> Result<Vec<Record<N, Rrsig<Octs, N>>>, SigningError> {
        let rrsig_config = GenerateRrsigConfig::new(inception, expiration);

        sign_sorted_zone_records(
            apex_owner,
            self.owner_rrs(),
            keys,
            &rrsig_config,
        )
    }
}

//--- impl Signable for Rrset

impl<N, Octs, Inner> Signable<N, Octs, Inner>
    for Rrset<'_, N, ZoneRecordData<Octs, N>>
where
    Inner: Debug + SignRaw,
    N: From<Name<Octs>>
        + PartialEq
        + Clone
        + Debug
        + Display
        + Send
        + CanonicalOrd
        + ToName,
    Octs: octseq::FromBuilder
        + Send
        + OctetsFrom<Vec<u8>>
        + Clone
        + Debug
        + From<&'static [u8]>
        + From<Box<[u8]>>,
    <Octs as FromBuilder>::Builder: AsRef<[u8]> + AsMut<[u8]> + EmptyBuilder,
{
    fn owner_rrs(&self) -> RecordsIter<'_, N, ZoneRecordData<Octs, N>> {
        RecordsIter::new(self.clone().into_inner())
    }
}