Skip to main content

instant_epp/extensions/
secdns.rs

1//! DNS security extensions mapping
2//!
3//! As described in [RFC 5910](https://www.rfc-editor.org/rfc/rfc5910)
4
5use std::borrow::Cow;
6use std::fmt::Write;
7use std::time::Duration;
8
9use instant_xml::ser::Context;
10use instant_xml::{Error, Id, Serializer, ToXml};
11
12use crate::common::NoExtension;
13use crate::request::{Extension, Transaction};
14
15pub const XMLNS: &str = "urn:ietf:params:xml:ns:secDNS-1.1";
16
17impl<'a> Transaction<CreateData<'a>> for crate::domain::create::DomainCreate<'a> {}
18
19impl Extension for CreateData<'_> {
20    type Response = NoExtension;
21}
22
23#[derive(Debug, ToXml)]
24#[xml(rename = "create", ns(XMLNS))]
25pub struct CreateData<'a> {
26    data: DsOrKeyType<'a>,
27}
28
29impl<'a> From<&'a [DsDataType<'a>]> for CreateData<'a> {
30    fn from(s: &'a [DsDataType<'a>]) -> Self {
31        Self {
32            data: DsOrKeyType {
33                maximum_signature_lifetime: None,
34                data: DsOrKeyData::DsData(s),
35            },
36        }
37    }
38}
39
40impl<'a> From<&'a [KeyDataType<'a>]> for CreateData<'a> {
41    fn from(s: &'a [KeyDataType<'a>]) -> Self {
42        Self {
43            data: DsOrKeyType {
44                maximum_signature_lifetime: None,
45                data: DsOrKeyData::KeyData(s),
46            },
47        }
48    }
49}
50
51impl<'a> From<(Duration, &'a [DsDataType<'a>])> for CreateData<'a> {
52    fn from((maximum_signature_lifetime, data): (Duration, &'a [DsDataType<'a>])) -> Self {
53        Self {
54            data: DsOrKeyType {
55                maximum_signature_lifetime: Some(maximum_signature_lifetime),
56                data: DsOrKeyData::DsData(data),
57            },
58        }
59    }
60}
61
62impl<'a> From<(Duration, &'a [KeyDataType<'a>])> for CreateData<'a> {
63    fn from((maximum_signature_lifetime, data): (Duration, &'a [KeyDataType<'a>])) -> Self {
64        Self {
65            data: DsOrKeyType {
66                maximum_signature_lifetime: Some(maximum_signature_lifetime),
67                data: DsOrKeyData::KeyData(data),
68            },
69        }
70    }
71}
72
73/// Struct supporting either the `dsData` or the `keyData` interface.
74#[derive(Debug)]
75pub struct DsOrKeyType<'a> {
76    maximum_signature_lifetime: Option<Duration>,
77    data: DsOrKeyData<'a>,
78}
79
80impl ToXml for DsOrKeyType<'_> {
81    fn serialize<W: Write + ?Sized>(
82        &self,
83        _: Option<Id<'_>>,
84        serializer: &mut Serializer<'_, W>,
85    ) -> Result<(), Error> {
86        if let Some(maximum_signature_lifetime) = self.maximum_signature_lifetime {
87            let max_sig_life = serializer.write_start("maxSigLife", XMLNS, None::<Context<0>>)?;
88            serializer.end_start()?;
89            maximum_signature_lifetime
90                .as_secs()
91                .serialize(None, serializer)?;
92            serializer.write_close(max_sig_life)?;
93        }
94
95        match &self.data {
96            DsOrKeyData::DsData(data) => data.serialize(None, serializer)?,
97            DsOrKeyData::KeyData(data) => data.serialize(None, serializer)?,
98        }
99        Ok(())
100    }
101}
102
103#[derive(Debug, ToXml)]
104#[xml(forward)]
105pub enum DsOrKeyData<'a> {
106    DsData(&'a [DsDataType<'a>]),
107    KeyData(&'a [KeyDataType<'a>]),
108}
109
110#[derive(Debug, ToXml)]
111#[xml(rename = "dsData", ns(XMLNS))]
112pub struct DsDataType<'a> {
113    #[xml(rename = "keyTag")]
114    key_tag: u16,
115    #[xml(rename = "alg")]
116    algorithm: Algorithm,
117    #[xml(rename = "digestType")]
118    digest_type: DigestAlgorithm,
119    digest: Cow<'a, str>,
120    #[xml(rename = "keyData")]
121    key_data: Option<KeyDataType<'a>>,
122}
123
124impl<'a> DsDataType<'a> {
125    pub fn new(
126        key_tag: u16,
127        algorithm: Algorithm,
128        digest_type: DigestAlgorithm,
129        digest: impl Into<Cow<'a, str>>,
130        key_data: Option<KeyDataType<'a>>,
131    ) -> Self {
132        Self {
133            key_tag,
134            algorithm,
135            digest_type,
136            digest: digest.into(),
137            key_data,
138        }
139    }
140}
141
142/// DigestAlgorithm identifies the algorithm used to construct the digest
143/// <https://www.iana.org/assignments/ds-rr-types/ds-rr-types.xhtml>
144#[derive(Clone, Copy, Debug)]
145// XXX Do NOT derive PartialEq, Hash or Ord because the variant
146// Other(u8) could clash with one of the other variants. They have to
147// be hand coded.
148pub enum DigestAlgorithm {
149    Sha1,
150    Sha256,
151    Gost,
152    Sha384,
153    Sm3,
154    Other(u8),
155}
156
157impl From<DigestAlgorithm> for u8 {
158    fn from(s: DigestAlgorithm) -> Self {
159        match s {
160            DigestAlgorithm::Sha1 => 1,
161            DigestAlgorithm::Sha256 => 2,
162            DigestAlgorithm::Gost => 3,
163            DigestAlgorithm::Sha384 => 4,
164            DigestAlgorithm::Sm3 => 6,
165            DigestAlgorithm::Other(n) => n,
166        }
167    }
168}
169
170impl ToXml for DigestAlgorithm {
171    fn serialize<W: Write + ?Sized>(
172        &self,
173        id: Option<Id<'_>>,
174        serializer: &mut Serializer<'_, W>,
175    ) -> Result<(), Error> {
176        u8::from(*self).serialize(id, serializer)
177    }
178}
179
180/// Algorithm identifies the public key's cryptographic algorithm
181/// <https://www.iana.org/assignments/dns-sec-alg-numbers/dns-sec-alg-numbers.xhtml#dns-sec-alg-numbers-1>
182#[derive(Clone, Copy, Debug)]
183// XXX Do NOT derive PartialEq, Hash or Ord because the variant
184// Other(u8) could clash with one of the other variants. They have to
185// be hand coded.
186pub enum Algorithm {
187    // Delete DS
188    Delete,
189    /// RSA/MD5
190    RsaMd5,
191    /// Diffie-Hellman
192    Dh,
193    /// DSA/SHA-1
194    Dsa,
195    /// Elliptic Curve
196    Ecc,
197    /// RSA/SHA-1
198    RsaSha1,
199    /// DSA-NSEC3-SHA1
200    DsaNsec3Sha1,
201    /// RSASHA1-NSEC3-SHA1
202    RsaSha1Nsec3Sha1,
203    /// RSA/SHA-256
204    RsaSha256,
205    /// RSA/SHA-512
206    RsaSha512,
207    /// GOST R 34.10-2001
208    EccGost,
209    /// ECDSA Curve P-256 with SHA-256
210    EcdsaP256Sha256,
211    /// ECDSA Curve P-384 with SHA-384
212    EcdsaP384Sha384,
213    /// Ed25519
214    Ed25519,
215    /// Ed448
216    Ed448,
217    /// SM2 signing algorithm with SM3 hashing algorithm
218    Sm2Sm3,
219    /// GOST R 34.10.2012
220    EccGost12,
221    /// Indirect
222    Indirect,
223    /// Private
224    PrivateDns,
225    /// Private
226    PrivateOid,
227    Other(u8),
228}
229
230impl From<Algorithm> for u8 {
231    fn from(s: Algorithm) -> Self {
232        match s {
233            Algorithm::Delete => 0,
234            Algorithm::RsaMd5 => 1,
235            Algorithm::Dh => 2,
236            Algorithm::Dsa => 3,
237            // RFC 4034
238            Algorithm::Ecc => 4,
239            Algorithm::RsaSha1 => 5,
240            Algorithm::DsaNsec3Sha1 => 6,
241            Algorithm::RsaSha1Nsec3Sha1 => 7,
242            Algorithm::RsaSha256 => 8,
243            Algorithm::RsaSha512 => 10,
244            Algorithm::EccGost => 12,
245            Algorithm::EcdsaP256Sha256 => 13,
246            Algorithm::EcdsaP384Sha384 => 14,
247            Algorithm::Ed25519 => 15,
248            Algorithm::Ed448 => 16,
249            Algorithm::Sm2Sm3 => 17,
250            Algorithm::EccGost12 => 23,
251            Algorithm::Indirect => 252,
252            Algorithm::PrivateDns => 253,
253            Algorithm::PrivateOid => 254,
254            Algorithm::Other(n) => n,
255        }
256    }
257}
258
259impl ToXml for Algorithm {
260    fn serialize<W: Write + ?Sized>(
261        &self,
262        id: Option<Id<'_>>,
263        serializer: &mut Serializer<'_, W>,
264    ) -> Result<(), Error> {
265        u8::from(*self).serialize(id, serializer)
266    }
267}
268
269#[derive(Debug, ToXml)]
270#[xml(rename = "keyData", ns(XMLNS))]
271pub struct KeyDataType<'a> {
272    flags: Flags,
273    protocol: Protocol,
274    #[xml(rename = "alg")]
275    algorithm: Algorithm,
276    #[xml(rename = "pubKey")]
277    public_key: Cow<'a, str>,
278}
279
280impl<'a> KeyDataType<'a> {
281    pub fn new(
282        flags: Flags,
283        protocol: Protocol,
284        algorithm: Algorithm,
285        public_key: &'a str,
286    ) -> Self {
287        Self {
288            flags,
289            protocol,
290            algorithm,
291            public_key: public_key.into(),
292        }
293    }
294}
295
296#[derive(Clone, Copy, Debug)]
297pub struct Flags {
298    /// Zone Key flag. If `true` then the DNSKEY record holds a DNS
299    /// zone key. If `false` then the DNSKEY record holds some other
300    /// type of DNS public key.
301    zone_key: bool,
302    /// Secure Entry Point. If `true` then the DNSKEY record holds a
303    /// key intended for use as a secure entry point.
304    secure_entry_point: bool,
305}
306
307impl From<Flags> for u16 {
308    fn from(flags: Flags) -> Self {
309        let mut res = 0;
310        if flags.zone_key {
311            res |= 0b1_0000_0000;
312        }
313        if flags.secure_entry_point {
314            res |= 0x1;
315        }
316        res
317    }
318}
319
320impl ToXml for Flags {
321    fn serialize<W: Write + ?Sized>(
322        &self,
323        id: Option<Id<'_>>,
324        serializer: &mut Serializer<'_, W>,
325    ) -> Result<(), Error> {
326        u16::from(*self).serialize(id, serializer)
327    }
328}
329
330/// `Flags` for a zone signing key.
331pub const FLAGS_DNS_ZONE_KEY: Flags = Flags {
332    zone_key: true,
333    secure_entry_point: false,
334};
335/// `Flags` for a key signing key.
336pub const FLAGS_DNS_ZONE_KEY_SEP: Flags = Flags {
337    zone_key: true,
338    secure_entry_point: true,
339};
340
341#[derive(Clone, Copy, Debug)]
342// XXX Do NOT derive PartialEq, Hash or Ord because the variant
343// Other(u8) could clash with one of the other variants. They have to
344// be hand coded.
345pub enum Protocol {
346    /// RFC 2535, reserved
347    Tls,
348    /// RFC 2535, reserved
349    Email,
350    /// RFC 5034 DNSSEC
351    Dnssec,
352    /// RFC 2535, reserved
353    Ipsec,
354    /// RFC 2535
355    All,
356    Other(u8),
357}
358
359impl From<Protocol> for u8 {
360    fn from(s: Protocol) -> Self {
361        match s {
362            Protocol::Tls => 1,
363            Protocol::Email => 2,
364            Protocol::Dnssec => 3,
365            Protocol::Ipsec => 4,
366            Protocol::All => 255,
367            Protocol::Other(n) => n,
368        }
369    }
370}
371
372impl ToXml for Protocol {
373    fn serialize<W: Write + ?Sized>(
374        &self,
375        id: Option<Id<'_>>,
376        serializer: &mut Serializer<'_, W>,
377    ) -> Result<(), Error> {
378        u8::from(*self).serialize(id, serializer)
379    }
380}
381
382#[cfg(test)]
383mod tests {
384    use super::*;
385    use crate::domain::{self, Period, PeriodLength};
386    use crate::tests::assert_serialized;
387
388    #[test]
389    fn create_ds_data_interface() {
390        let ds_data = [DsDataType::new(
391            12345,
392            Algorithm::Dsa,
393            DigestAlgorithm::Sha1,
394            "49FD46E6C4B45C55D4AC",
395            None,
396        )];
397        let extension = CreateData::from((Duration::from_secs(604800), ds_data.as_ref()));
398        let ns = [
399            domain::HostInfo::Obj(domain::HostObj {
400                name: "ns1.example.com".into(),
401            }),
402            domain::HostInfo::Obj(domain::HostObj {
403                name: "ns2.example.com".into(),
404            }),
405        ];
406        let contact = [
407            domain::DomainContact {
408                contact_type: "admin".into(),
409                id: "sh8013".into(),
410            },
411            domain::DomainContact {
412                contact_type: "tech".into(),
413                id: "sh8013".into(),
414            },
415        ];
416        let object = domain::DomainCreate::new(
417            "example.com",
418            Period::Years(PeriodLength::new(2).unwrap()),
419            Some(&ns),
420            Some("jd1234"),
421            "2fooBAR",
422            Some(&contact),
423        );
424        assert_serialized(
425            "request/extensions/secdns_create_ds.xml",
426            (&object, &extension),
427        );
428    }
429
430    #[test]
431    fn create_ds_and_key_data_interface() {
432        let key_data = KeyDataType::new(
433            FLAGS_DNS_ZONE_KEY_SEP,
434            Protocol::Dnssec,
435            Algorithm::Dsa,
436            "AQPJ////4Q==",
437        );
438        let ds_data = [DsDataType::new(
439            12345,
440            Algorithm::Dsa,
441            DigestAlgorithm::Sha1,
442            "49FD46E6C4B45C55D4AC",
443            Some(key_data),
444        )];
445        let extension = CreateData::from((Duration::from_secs(604800), ds_data.as_ref()));
446        let ns = [
447            domain::HostInfo::Obj(domain::HostObj {
448                name: "ns1.example.com".into(),
449            }),
450            domain::HostInfo::Obj(domain::HostObj {
451                name: "ns2.example.com".into(),
452            }),
453        ];
454        let contact = [
455            domain::DomainContact {
456                contact_type: "admin".into(),
457                id: "sh8013".into(),
458            },
459            domain::DomainContact {
460                contact_type: "tech".into(),
461                id: "sh8013".into(),
462            },
463        ];
464        let object = domain::DomainCreate::new(
465            "example.com",
466            Period::Years(PeriodLength::new(2).unwrap()),
467            Some(&ns),
468            Some("jd1234"),
469            "2fooBAR",
470            Some(&contact),
471        );
472        assert_serialized(
473            "request/extensions/secdns_create_ds_key.xml",
474            (&object, &extension),
475        );
476    }
477
478    #[test]
479    fn create_key_data_interface() {
480        let key_data = [KeyDataType::new(
481            FLAGS_DNS_ZONE_KEY_SEP,
482            Protocol::Dnssec,
483            Algorithm::RsaMd5,
484            "AQPJ////4Q==",
485        )];
486        let extension = CreateData::from(key_data.as_ref());
487        let ns = [
488            domain::HostInfo::Obj(domain::HostObj {
489                name: "ns1.example.com".into(),
490            }),
491            domain::HostInfo::Obj(domain::HostObj {
492                name: "ns2.example.com".into(),
493            }),
494        ];
495        let contact = [
496            domain::DomainContact {
497                contact_type: "admin".into(),
498                id: "sh8013".into(),
499            },
500            domain::DomainContact {
501                contact_type: "tech".into(),
502                id: "sh8013".into(),
503            },
504        ];
505        let object = domain::DomainCreate::new(
506            "example.com",
507            Period::Years(PeriodLength::new(2).unwrap()),
508            Some(&ns),
509            Some("jd1234"),
510            "2fooBAR",
511            Some(&contact),
512        );
513        assert_serialized(
514            "request/extensions/secdns_create_key.xml",
515            (&object, &extension),
516        );
517    }
518}