Skip to main content

hickory_proto/rr/rdata/
cert.rs

1// Copyright 2024 Brian Taber <btaber@zsd.systems>
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// https://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! CERT record type for storing certificates in DNS
9use alloc::string::String;
10use alloc::vec::Vec;
11use core::fmt;
12use core::str::FromStr;
13
14#[cfg(feature = "serde")]
15use serde::{Deserialize, Serialize};
16
17use crate::{
18    error::ProtoResult,
19    rr::{RData, RecordData, RecordDataDecodable, RecordType},
20    serialize::{
21        binary::{
22            BinDecodable, BinDecoder, BinEncodable, BinEncoder, DecodeError, RDataEncoding,
23            Restrict, RestrictedMath,
24        },
25        txt::ParseError,
26    },
27};
28
29/// [RFC 4398, Storing Certificates in DNS, November 1987](https://tools.ietf.org/html/rfc4398#section-2.1)
30///
31/// ```text
32/// [2.1](https://datatracker.ietf.org/doc/html/rfc4398#section-2.1).  Certificate Type Values
33///
34///    The following values are defined or reserved:
35///
36///          Value  Mnemonic  Certificate Type
37///          -----  --------  ----------------
38///              0            Reserved
39///              1  PKIX      X.509 as per PKIX
40///              2  SPKI      SPKI certificate
41///              3  PGP       OpenPGP packet
42///              4  IPKIX     The URL of an X.509 data object
43///              5  ISPKI     The URL of an SPKI certificate
44///              6  IPGP      The fingerprint and URL of an OpenPGP packet
45///              7  ACPKIX    Attribute Certificate
46///              8  IACPKIX   The URL of an Attribute Certificate
47///          9-252            Available for IANA assignment
48///            253  URI       URI private
49///            254  OID       OID private
50///            255            Reserved
51///      256-65279            Available for IANA assignment
52///    65280-65534            Experimental
53///          65535            Reserved
54/// ```
55#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
56#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
57pub enum CertType {
58    /// 0            Reserved
59    Reserved0,
60
61    /// 1  PKIX      X.509 as per PKIX
62    PKIX,
63
64    /// 2  SPKI      SPKI certificate
65    SPKI,
66
67    /// 3  PGP       OpenPGP packet
68    PGP,
69
70    /// 4  IPKIX     The URL of an X.509 data object
71    IPKIX,
72
73    /// 5  ISPKI     The URL of an SPKI certificate
74    ISPKI,
75
76    /// 6  IPGP      The fingerprint and URL of an OpenPGP packet
77    IPGP,
78
79    /// 7  ACPKIX    Attribute Certificate
80    ACPKIX,
81
82    /// 8  IACPKIX   The URL of an Attribute Certificate
83    IACPKIX,
84
85    /// 253  URI       URI private
86    URI,
87
88    /// 254  OID       OID private
89    OID,
90
91    /// 255          Reserved
92    Reserved255,
93
94    /// 9-252, 256-65279            Available for IANA assignment
95    Unassigned(u16),
96
97    /// 65280-65534            Experimental
98    Experimental(u16),
99
100    /// 65535        Reserved
101    Reserved65535,
102}
103
104impl From<u16> for CertType {
105    fn from(cert_type: u16) -> Self {
106        match cert_type {
107            0 => Self::Reserved0,
108            1 => Self::PKIX,
109            2 => Self::SPKI,
110            3 => Self::PGP,
111            4 => Self::IPKIX,
112            5 => Self::ISPKI,
113            6 => Self::IPGP,
114            7 => Self::ACPKIX,
115            8 => Self::IACPKIX,
116            9_u16..=252_u16 => Self::Unassigned(cert_type),
117            253 => Self::URI,
118            254 => Self::OID,
119            255 => Self::Reserved255,
120            256_u16..=65279_u16 => Self::Unassigned(cert_type),
121            65280_u16..=65534_u16 => Self::Experimental(cert_type),
122            65535 => Self::Reserved65535,
123        }
124    }
125}
126
127impl From<CertType> for u16 {
128    fn from(cert_type: CertType) -> Self {
129        match cert_type {
130            CertType::Reserved0 => 0,
131            CertType::PKIX => 1,
132            CertType::SPKI => 2,
133            CertType::PGP => 3,
134            CertType::IPKIX => 4,
135            CertType::ISPKI => 5,
136            CertType::IPGP => 6,
137            CertType::ACPKIX => 7,
138            CertType::IACPKIX => 8,
139            CertType::URI => 253,
140            CertType::OID => 254,
141            CertType::Reserved255 => 255,
142            CertType::Unassigned(cert_type) => cert_type,
143            CertType::Experimental(cert_type) => cert_type,
144            CertType::Reserved65535 => 65535,
145        }
146    }
147}
148
149impl<'r> BinDecodable<'r> for CertType {
150    fn read(decoder: &mut BinDecoder<'r>) -> Result<Self, DecodeError> {
151        let algorithm_id = decoder
152            .read_u16()?
153            .unverified(/*CertType is verified as safe in processing this*/);
154        Ok(Self::from(algorithm_id))
155    }
156}
157
158impl FromStr for CertType {
159    type Err = ParseError;
160
161    /// Parses a certificate type from its decimal value or its mnemonic
162    /// ([RFC 4398 section 2.2](https://datatracker.ietf.org/doc/html/rfc4398#section-2.2))
163    fn from_str(s: &str) -> Result<Self, Self::Err> {
164        if let Ok(value) = u16::from_str(s) {
165            return Ok(Self::from(value));
166        }
167
168        Ok(match s {
169            s if s.eq_ignore_ascii_case("PKIX") => Self::PKIX,
170            s if s.eq_ignore_ascii_case("SPKI") => Self::SPKI,
171            s if s.eq_ignore_ascii_case("PGP") => Self::PGP,
172            s if s.eq_ignore_ascii_case("IPKIX") => Self::IPKIX,
173            s if s.eq_ignore_ascii_case("ISPKI") => Self::ISPKI,
174            s if s.eq_ignore_ascii_case("IPGP") => Self::IPGP,
175            s if s.eq_ignore_ascii_case("ACPKIX") => Self::ACPKIX,
176            s if s.eq_ignore_ascii_case("IACPKIX") => Self::IACPKIX,
177            s if s.eq_ignore_ascii_case("URI") => Self::URI,
178            s if s.eq_ignore_ascii_case("OID") => Self::OID,
179            _ => return Err(ParseError::from("Invalid digit found in cert_type token")),
180        })
181    }
182}
183
184impl fmt::Display for CertType {
185    /// Writes the mnemonic of the certificate type if it has one, its decimal value otherwise
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        match self {
188            Self::PKIX => f.write_str("PKIX"),
189            Self::SPKI => f.write_str("SPKI"),
190            Self::PGP => f.write_str("PGP"),
191            Self::IPKIX => f.write_str("IPKIX"),
192            Self::ISPKI => f.write_str("ISPKI"),
193            Self::IPGP => f.write_str("IPGP"),
194            Self::ACPKIX => f.write_str("ACPKIX"),
195            Self::IACPKIX => f.write_str("IACPKIX"),
196            Self::URI => f.write_str("URI"),
197            Self::OID => f.write_str("OID"),
198            _ => write!(f, "{}", u16::from(*self)),
199        }
200    }
201}
202
203/// [RFC 4398, Storing Certificates in DNS, November 1987](https://tools.ietf.org/html/rfc4398#section-2.2)
204///
205/// ```text
206///
207/// [2.2](https://datatracker.ietf.org/doc/html/rfc4398#section-2.2).  Text Representation of CERT RRs
208///
209///    The RDATA portion of a CERT RR has the type field as an unsigned
210///    decimal integer or as a mnemonic symbol as listed in [Section 2.1](https://datatracker.ietf.org/doc/html/rfc4398#section-2.1),
211///    above.
212///
213///    The key tag field is represented as an unsigned decimal integer.
214///
215///    The algorithm field is represented as an unsigned decimal integer or
216///    a mnemonic symbol as listed in [[12](https://datatracker.ietf.org/doc/html/rfc4398#ref-12)].
217///
218/// [12]  Arends, R., Austein, R., Larson, M., Massey, D., and S. Rose,
219/// "Resource Records for the DNS Security Extensions", RFC 4034,
220/// March 2005.
221///
222///
223/// [RFC 4034, Resource Records for the DNS Security Extensions, March 2005][rfc4034]
224/// https://tools.ietf.org/html/rfc4034#appendix-A.1
225///
226/// [A.1](https://datatracker.ietf.org/doc/html/rfc4034#appendix-A.1).  DNSSEC Algorithm Types
227///
228///    The DNSKEY, RRSIG, and DS RRs use an 8-bit number to identify the
229///    security algorithm being used.  These values are stored in the
230///    "Algorithm number" field in the resource record RDATA.
231///
232///    Some algorithms are usable only for zone signing (DNSSEC), some only
233///    for transaction security mechanisms (SIG(0) and TSIG), and some for
234///    both.  Those usable for zone signing may appear in DNSKEY, RRSIG, and
235///    DS RRs.  Those usable for transaction security would be present in
236///    SIG(0) and KEY RRs, as described in [RFC2931].
237///
238///                                 Zone
239///    Value Algorithm [Mnemonic]  Signing  References   Status
240///    ----- -------------------- --------- ----------  ---------
241///      0   reserved
242///      1   RSA/MD5 [RSAMD5]         n      [RFC2537]  NOT RECOMMENDED
243///      2   Diffie-Hellman [DH]      n      [RFC2539]   -
244///      3   DSA/SHA-1 [DSA]          y      [RFC2536]  OPTIONAL
245///      4   Elliptic Curve [ECC]              TBA       -
246///      5   RSA/SHA-1 [RSASHA1]      y      [RFC3110]  MANDATORY
247///    252   Indirect [INDIRECT]      n                  -
248///    253   Private [PRIVATEDNS]     y      see below  OPTIONAL
249///    254   Private [PRIVATEOID]     y      see below  OPTIONAL
250///    255   reserved
251///
252///    6 - 251  Available for assignment by IETF Standards Action.
253///
254/// (RFC Required) Domain Name System Security (DNSSEC) Algorithm Numbers
255/// Created: 2003-11-03, Last Updated: 2024-04-16
256/// https://www.iana.org/assignments/dns-sec-alg-numbers/dns-sec-alg-numbers.txt
257///
258///                                                              Zone
259///     Value  Algorithm [Mnemonic]                            Signing    References
260///     -----  --------------------                           ---------   ----------
261///       6    DSA-NSEC3-SHA1 [DSA-NSEC3-SHA1]                    Y       [RFC5155][proposed standard]
262///       7    RSASHA1-NSEC3-SHA1 [RSASHA1-NSEC3-SHA1]            Y       [RFC5155][proposed standard]
263///       8    RSA/SHA-256 [RSASHA256]                            Y       [RFC5702][proposed standard]
264///       9    reserved
265///      10    RSA/SHA-512 [RSASHA512]                            Y       [RFC5702][proposed standard]
266///      11    reserved
267///      12    GOST R 34.10-2001 [ECC-GOST]                       Y       [RFC5933][proposed standard]
268///      13    ECDSA Curve P-256 with SHA-256 [ECDSAP256SHA256]   Y       [RFC6605][proposed standard]
269///      14    ECDSA Curve P-384 with SHA-384 [ECDSAP384SHA384]   Y       [RFC6605][proposed standard]
270///      15    Ed25519 [ED25519]                                  Y       [RFC8080][proposed standard]
271///      16    Ed448 [ED448]                                      Y       [RFC8080][proposed standard]
272///      17    SM2 signing with SM3 hashing [SM2SM3]              Y       [RFC-cuiling-dnsop-sm2-alg-15][informational]
273///   18-22    Unassigned
274///      23    GOST R 34.10-2012 [ECC-GOST12]                     Y       [RFC9558][informational]
275///  24-122    Unassigned
276/// 123-251    reserved
277/// ```
278#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
279#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
280pub enum Algorithm {
281    /// 0, 9, 11, 123-251, 255   reserved
282    Reserved(u8),
283
284    /// 1   RSA/MD5 ([RFC 2537](https://tools.ietf.org/html/rfc2537))
285    RSAMD5,
286
287    /// 2   Diffie-Hellman ([RFC 2539](https://tools.ietf.org/html/rfc2539))
288    DH,
289
290    /// 3   DSA/SHA-1 ([RFC 2536](https://tools.ietf.org/html/rfc2536))
291    DSA,
292
293    /// 4   Elliptic Curve
294    ECC,
295
296    /// 5   RSA/SHA-1 ([RFC 3110](https://tools.ietf.org/html/rfc3110))
297    RSASHA1,
298
299    /// 252   Indirect
300    INDIRECT,
301
302    /// 253   Private
303    PRIVATEDNS,
304
305    /// 254   Private
306    PRIVATEOID,
307
308    /// 6    DSA-NSEC3-SHA1 ([RFC 5155](https://tools.ietf.org/html/rfc5155))
309    DSANSEC3SHA1,
310
311    /// 7    RSASHA1-NSEC3-SHA1 (RFC5155)
312    RSASHA1NSEC3SHA1,
313
314    /// 8    RSA/SHA-256 ([RFC 5702](https://tools.ietf.org/html/rfc5702))
315    RSASHA256,
316
317    /// 10    RSA/SHA-512 ([RFC 5702](https://tools.ietf.org/html/rfc5702))
318    RSASHA512,
319
320    /// 12    GOST R 34.10-2001 ([RFC 5933](https://tools.ietf.org/html/rfc5933))
321    ECCGOST,
322
323    /// 13    ECDSA Curve P-256 with SHA-256 ([RFC 6605](https://tools.ietf.org/html/rfc6605))
324    ECDSAP256SHA256,
325
326    /// 14    ECDSA Curve P-384 with SHA-384 ([RFC 6605](https://tools.ietf.org/html/rfc6605))
327    ECDSAP384SHA384,
328
329    /// 15    Ed25519 ([RFC 8080](https://tools.ietf.org/html/rfc8080))
330    ED25519,
331
332    /// 16    Ed448 ([RFC 8080](https://tools.ietf.org/html/rfc8080))
333    ED448,
334
335    /// 17    SM2 signing with SM3 hashing (RFC-cuiling-dnsop-sm2-alg-15)
336    SM2SM3,
337
338    /// 23    GOST R 34.10-2012 ([RFC 9558](https://tools.ietf.org/html/rfc9558))
339    ECCGOST12,
340
341    ///   18-22, 24-122    Unassigned
342    Unassigned(u8),
343}
344
345impl From<u8> for Algorithm {
346    fn from(algorithm: u8) -> Self {
347        match algorithm {
348            0 => Self::Reserved(0),
349            1 => Self::RSAMD5,
350            2 => Self::DH,
351            3 => Self::DSA,
352            4 => Self::ECC,
353            5 => Self::RSASHA1,
354            6 => Self::DSANSEC3SHA1,
355            7 => Self::RSASHA1NSEC3SHA1,
356            8 => Self::RSASHA256,
357            9 => Self::Reserved(9),
358            10 => Self::RSASHA512,
359            11 => Self::Reserved(11),
360            12 => Self::ECCGOST,
361            13 => Self::ECDSAP256SHA256,
362            14 => Self::ECDSAP384SHA384,
363            15 => Self::ED25519,
364            16 => Self::ED448,
365            17 => Self::SM2SM3,
366            18..=22 => Self::Unassigned(algorithm),
367            23 => Self::ECCGOST12,
368            24..=122 => Self::Unassigned(algorithm),
369            252 => Self::INDIRECT,
370            253 => Self::PRIVATEDNS,
371            254 => Self::PRIVATEOID,
372            _ => Self::Unassigned(algorithm),
373        }
374    }
375}
376
377impl From<Algorithm> for u8 {
378    fn from(algorithm: Algorithm) -> Self {
379        match algorithm {
380            Algorithm::Reserved(value) if value == 0 => value,
381            Algorithm::RSAMD5 => 1,
382            Algorithm::DH => 2,
383            Algorithm::DSA => 3,
384            Algorithm::ECC => 4,
385            Algorithm::RSASHA1 => 5,
386            Algorithm::DSANSEC3SHA1 => 6,
387            Algorithm::RSASHA1NSEC3SHA1 => 7,
388            Algorithm::RSASHA256 => 8,
389            Algorithm::Reserved(value) if value == 9 => value,
390            Algorithm::RSASHA512 => 10,
391            Algorithm::Reserved(value) if value == 11 => value,
392            Algorithm::ECCGOST => 12,
393            Algorithm::ECDSAP256SHA256 => 13,
394            Algorithm::ECDSAP384SHA384 => 14,
395            Algorithm::ED25519 => 15,
396            Algorithm::ED448 => 16,
397            Algorithm::SM2SM3 => 17,
398            Algorithm::Unassigned(value) if (18..=22).contains(&value) => value,
399            Algorithm::ECCGOST12 => 23,
400            Algorithm::Unassigned(value) if (24..=122).contains(&value) => value,
401            Algorithm::INDIRECT => 252,
402            Algorithm::PRIVATEDNS => 253,
403            Algorithm::PRIVATEOID => 254,
404            Algorithm::Unassigned(value) => value,
405            Algorithm::Reserved(value) => value,
406        }
407    }
408}
409
410impl<'r> BinDecodable<'r> for Algorithm {
411    // https://www.iana.org/assignments/dns-sec-alg-numbers/dns-sec-alg-numbers.xhtml
412    fn read(decoder: &mut BinDecoder<'r>) -> Result<Self, DecodeError> {
413        let algorithm_id = decoder
414            .read_u8()?
415            .unverified(/*Algorithm is verified as safe in processing this*/);
416        Ok(Self::from(algorithm_id))
417    }
418}
419
420impl FromStr for Algorithm {
421    type Err = ParseError;
422
423    /// Parses an algorithm from its decimal value or its DNSSEC mnemonic
424    /// ([RFC 4398 section 2.2](https://datatracker.ietf.org/doc/html/rfc4398#section-2.2))
425    fn from_str(s: &str) -> Result<Self, Self::Err> {
426        if let Ok(value) = u8::from_str(s) {
427            return Ok(Self::from(value));
428        }
429
430        Ok(match s {
431            s if s.eq_ignore_ascii_case("RSAMD5") => Self::RSAMD5,
432            s if s.eq_ignore_ascii_case("DH") => Self::DH,
433            s if s.eq_ignore_ascii_case("DSA") => Self::DSA,
434            s if s.eq_ignore_ascii_case("ECC") => Self::ECC,
435            s if s.eq_ignore_ascii_case("RSASHA1") => Self::RSASHA1,
436            s if s.eq_ignore_ascii_case("DSA-NSEC3-SHA1") || s.eq_ignore_ascii_case("NSEC3DSA") => {
437                Self::DSANSEC3SHA1
438            }
439            s if s.eq_ignore_ascii_case("RSASHA1-NSEC3-SHA1")
440                || s.eq_ignore_ascii_case("NSEC3RSASHA1") =>
441            {
442                Self::RSASHA1NSEC3SHA1
443            }
444            s if s.eq_ignore_ascii_case("RSASHA256") => Self::RSASHA256,
445            s if s.eq_ignore_ascii_case("RSASHA512") => Self::RSASHA512,
446            s if s.eq_ignore_ascii_case("ECC-GOST") || s.eq_ignore_ascii_case("ECCGOST") => {
447                Self::ECCGOST
448            }
449            s if s.eq_ignore_ascii_case("ECDSAP256SHA256") => Self::ECDSAP256SHA256,
450            s if s.eq_ignore_ascii_case("ECDSAP384SHA384") => Self::ECDSAP384SHA384,
451            s if s.eq_ignore_ascii_case("ED25519") => Self::ED25519,
452            s if s.eq_ignore_ascii_case("ED448") => Self::ED448,
453            s if s.eq_ignore_ascii_case("SM2SM3") => Self::SM2SM3,
454            s if s.eq_ignore_ascii_case("ECC-GOST12") || s.eq_ignore_ascii_case("ECCGOST12") => {
455                Self::ECCGOST12
456            }
457            s if s.eq_ignore_ascii_case("INDIRECT") => Self::INDIRECT,
458            s if s.eq_ignore_ascii_case("PRIVATEDNS") => Self::PRIVATEDNS,
459            s if s.eq_ignore_ascii_case("PRIVATEOID") => Self::PRIVATEOID,
460            _ => return Err(ParseError::from("Invalid digit found in algorithm token")),
461        })
462    }
463}
464
465impl fmt::Display for Algorithm {
466    /// Writes the mnemonic of the algorithm, or its decimal value for algorithms without a
467    /// mnemonic that zone file parsers agree on
468    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
469        match self {
470            Self::RSAMD5 => f.write_str("RSAMD5"),
471            Self::DH => f.write_str("DH"),
472            Self::DSA => f.write_str("DSA"),
473            Self::RSASHA1 => f.write_str("RSASHA1"),
474            Self::RSASHA256 => f.write_str("RSASHA256"),
475            Self::RSASHA512 => f.write_str("RSASHA512"),
476            Self::ECDSAP256SHA256 => f.write_str("ECDSAP256SHA256"),
477            Self::ECDSAP384SHA384 => f.write_str("ECDSAP384SHA384"),
478            Self::ED25519 => f.write_str("ED25519"),
479            Self::ED448 => f.write_str("ED448"),
480            Self::INDIRECT => f.write_str("INDIRECT"),
481            Self::PRIVATEDNS => f.write_str("PRIVATEDNS"),
482            Self::PRIVATEOID => f.write_str("PRIVATEOID"),
483            _ => write!(f, "{}", u8::from(*self)),
484        }
485    }
486}
487
488/// [RFC 4398, Storing Certificates in DNS, November 1987](https://tools.ietf.org/html/rfc4398)
489///
490/// ```text
491///
492/// [2](https://datatracker.ietf.org/doc/html/rfc4398#section-2).  The CERT Resource Record
493///
494///    The CERT resource record (RR) has the structure given below.  Its RR
495///    type code is 37.
496///
497///       1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
498///    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
499///    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
500///    |             type              |             key tag           |
501///    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
502///    |   algorithm   |                                               /
503///    +---------------+            certificate or CRL                 /
504///    /                                                               /
505///    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-|
506/// ```
507#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
508#[derive(Debug, PartialEq, Eq, Hash, Clone)]
509#[non_exhaustive]
510pub struct CERT {
511    /// The CERT type
512    pub cert_type: CertType,
513
514    /// The CERT key tag
515    pub key_tag: u16,
516
517    /// The CERT algorithm
518    pub algorithm: Algorithm,
519
520    /// The CERT record data
521    ///
522    /// The data stored here is **not** base64-encoded. Use the `cert_base64()` function
523    /// if you need the data in base64-encoded format.
524    pub cert_data: Vec<u8>,
525}
526
527impl CERT {
528    /// Construct a new CERT RData
529    pub const fn new(
530        cert_type: CertType,
531        key_tag: u16,
532        algorithm: Algorithm,
533        cert_data: Vec<u8>,
534    ) -> Self {
535        Self {
536            cert_type,
537            key_tag,
538            algorithm,
539            cert_data,
540        }
541    }
542
543    /// Parse the RData from a set of Tokens
544    pub(crate) fn from_tokens<'i, I: Iterator<Item = &'i str>>(
545        tokens: I,
546    ) -> Result<Self, ParseError> {
547        let mut iter = tokens;
548
549        let token = iter
550            .next()
551            .ok_or_else(|| ParseError::from("CERT cert type field missing"))?;
552        let cert_type = CertType::from_str(token)?;
553
554        let token = iter
555            .next()
556            .ok_or(ParseError::Message("CERT key tag field missing"))?;
557        let key_tag = u16::from_str(token)
558            .map_err(|_| ParseError::Message("Invalid digit found in key_tag token"))?;
559
560        let token = iter
561            .next()
562            .ok_or_else(|| ParseError::from("CERT algorithm field missing"))?;
563        let algorithm = Algorithm::from_str(token)?;
564
565        // the base64 data may be split into several whitespace separated tokens
566        let cert_data = iter.collect::<String>();
567        if cert_data.is_empty() {
568            return Err(ParseError::from("CERT data missing"));
569        }
570
571        let cert_data = data_encoding::BASE64
572            .decode(cert_data.as_bytes())
573            .map_err(|_| ParseError::from("Invalid base64 CERT data"))?;
574
575        Ok(Self::new(cert_type, key_tag, algorithm, cert_data))
576    }
577
578    /// Returns the CERT (Base64)
579    pub fn cert_base64(&self) -> String {
580        data_encoding::BASE64.encode(&self.cert_data).clone()
581    }
582}
583
584impl TryFrom<&[u8]> for CERT {
585    type Error = DecodeError;
586
587    fn try_from(cert_record: &[u8]) -> Result<Self, Self::Error> {
588        let mut decoder = BinDecoder::new(cert_record);
589        let length = Restrict::new(cert_record.len() as u16); // You can use the full length here
590        Self::read_data(&mut decoder, length) // Reuse the read_data method for parsing
591    }
592}
593
594impl BinEncodable for CERT {
595    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
596        let mut encoder = encoder.with_rdata_behavior(RDataEncoding::Other);
597        encoder.emit_u16(self.cert_type.into())?;
598        encoder.emit_u16(self.key_tag)?;
599        encoder.emit_u8(self.algorithm.into())?;
600        encoder.emit_vec(&self.cert_data)?;
601
602        Ok(())
603    }
604}
605
606impl<'r> RecordDataDecodable<'r> for CERT {
607    fn read_data(decoder: &mut BinDecoder<'r>, length: Restrict<u16>) -> Result<Self, DecodeError> {
608        let rdata_length = length.map(|u| u as usize).unverified(/*used only as length safely*/);
609
610        if rdata_length <= 5 {
611            return Err(DecodeError::IncorrectRDataLengthRead {
612                read: rdata_length,
613                len: 6,
614            });
615        }
616
617        let start_idx = decoder.index();
618
619        // let cert_type = decoder.read_u16()?.unverified(/*valid as any u16*/);
620        let cert_type = CertType::read(decoder)?;
621        let key_tag = decoder.read_u16()?.unverified(/*valid as any u16*/);
622        let algorithm = Algorithm::read(decoder)?;
623
624        let cert_len = length
625            .map(|u| u as usize)
626            .checked_sub(decoder.index() - start_idx)
627            .map_err(|len| DecodeError::IncorrectRDataLengthRead { read: decoder.index() - start_idx, len })?
628            .unverified(/*used only as length safely*/);
629
630        let cert_data = decoder.read_vec(cert_len)?.unverified(/*will fail in usage if invalid*/);
631
632        Ok(Self {
633            cert_type,
634            key_tag,
635            algorithm,
636            cert_data,
637        })
638    }
639}
640
641impl RecordData for CERT {
642    fn try_borrow(data: &RData) -> Option<&Self> {
643        match data {
644            RData::CERT(data) => Some(data),
645            _ => None,
646        }
647    }
648
649    fn record_type(&self) -> RecordType {
650        RecordType::CERT
651    }
652
653    fn into_rdata(self) -> RData {
654        RData::CERT(self)
655    }
656}
657
658/// [RFC 4398, Storing Certificates in DNS, November 1987](https://tools.ietf.org/html/rfc4398#section-2.2)
659///
660/// ```text
661///
662/// [2.2](https://datatracker.ietf.org/doc/html/rfc4398#section-2.2).  Text Representation of CERT RRs
663///
664///    The RDATA portion of a CERT RR has the type field as an unsigned
665///    decimal integer or as a mnemonic symbol as listed in [Section 2.1](https://datatracker.ietf.org/doc/html/rfc4398#section-2.1),
666///    above.
667///
668///    The key tag field is represented as an unsigned decimal integer.
669///
670///    The algorithm field is represented as an unsigned decimal integer or
671///    a mnemonic symbol as listed in [[12](https://datatracker.ietf.org/doc/html/rfc4398#ref-12)].
672///
673///    The certificate/CRL portion is represented in base 64 [[16](https://datatracker.ietf.org/doc/html/rfc4398#ref-16)] and may be
674///    divided into any number of white-space-separated substrings, down to
675///    single base-64 digits, which are concatenated to obtain the full
676///    signature.  These substrings can span lines using the standard
677///    parenthesis.
678///
679///    Note that the certificate/CRL portion may have internal sub-fields,
680///    but these do not appear in the master file representation.  For
681///    example, with type 254, there will be an OID size, an OID, and then
682///    the certificate/CRL proper.  However, only a single logical base-64
683///    string will appear in the text representation.
684///
685/// ```
686impl fmt::Display for CERT {
687    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
688        let cert_data = &data_encoding::BASE64.encode(&self.cert_data);
689
690        write!(
691            f,
692            "{cert_type} {key_tag} {algorithm} {cert_data}",
693            cert_type = self.cert_type,
694            key_tag = self.key_tag,
695            algorithm = self.algorithm,
696            cert_data = cert_data
697        )?;
698
699        Ok(())
700    }
701}
702
703#[cfg(test)]
704mod tests {
705    #![allow(clippy::dbg_macro, clippy::print_stdout)]
706
707    use alloc::string::ToString;
708
709    use super::*;
710
711    #[test]
712    fn test_cert_type() {
713        assert_eq!(CertType::Reserved0, CertType::from(0));
714        assert_eq!(CertType::PKIX, CertType::from(1));
715        assert_eq!(CertType::SPKI, CertType::from(2));
716        assert_eq!(CertType::PGP, CertType::from(3));
717        assert_eq!(CertType::IPKIX, CertType::from(4));
718        assert_eq!(CertType::ISPKI, CertType::from(5));
719        assert_eq!(CertType::IPGP, CertType::from(6));
720        assert_eq!(CertType::ACPKIX, CertType::from(7));
721        assert_eq!(CertType::IACPKIX, CertType::from(8));
722        assert_eq!(CertType::URI, CertType::from(253));
723        assert_eq!(CertType::OID, CertType::from(254));
724        assert_eq!(CertType::Reserved255, CertType::from(255));
725        assert_eq!(CertType::Unassigned(9), CertType::from(9));
726        assert_eq!(CertType::Unassigned(90), CertType::from(90));
727        assert_eq!(CertType::Experimental(65280), CertType::from(65280));
728        assert_eq!(CertType::Experimental(65390), CertType::from(65390));
729        assert_eq!(CertType::Reserved65535, CertType::from(65535));
730
731        let cert_type_iana_9 = CertType::Unassigned(9);
732        let cert_type_iana_90 = CertType::Unassigned(90);
733        let cert_type_experimental_80 = CertType::Experimental(65280);
734        let cert_type_experimental_90 = CertType::Experimental(65290);
735
736        assert_eq!(u16::from(CertType::Reserved0), 0);
737        assert_eq!(u16::from(CertType::PKIX), 1);
738        assert_eq!(u16::from(CertType::SPKI), 2);
739        assert_eq!(u16::from(CertType::PGP), 3);
740        assert_eq!(u16::from(CertType::IPKIX), 4);
741        assert_eq!(u16::from(CertType::ISPKI), 5);
742        assert_eq!(u16::from(CertType::IPGP), 6);
743        assert_eq!(u16::from(CertType::ACPKIX), 7);
744        assert_eq!(u16::from(CertType::IACPKIX), 8);
745        assert_eq!(u16::from(cert_type_iana_9), 9);
746        assert_eq!(u16::from(cert_type_iana_90), 90);
747        assert_eq!(u16::from(CertType::URI), 253);
748        assert_eq!(u16::from(CertType::OID), 254);
749        assert_eq!(u16::from(CertType::Reserved255), 255);
750        assert_eq!(u16::from(cert_type_experimental_80), 65280);
751        assert_eq!(u16::from(cert_type_experimental_90), 65290);
752        assert_eq!(u16::from(CertType::Reserved65535), 65535);
753    }
754
755    #[test]
756    fn test_algorithm() {
757        assert_eq!(Algorithm::Reserved(0), Algorithm::from(0));
758        assert_eq!(Algorithm::DH, Algorithm::from(2));
759        assert_eq!(Algorithm::DSA, Algorithm::from(3));
760        assert_eq!(Algorithm::ECC, Algorithm::from(4));
761        assert_eq!(Algorithm::RSASHA1, Algorithm::from(5));
762        assert_eq!(Algorithm::DSANSEC3SHA1, Algorithm::from(6));
763        assert_eq!(Algorithm::RSASHA1NSEC3SHA1, Algorithm::from(7));
764        assert_eq!(Algorithm::RSASHA256, Algorithm::from(8));
765        assert_eq!(Algorithm::Reserved(9), Algorithm::from(9));
766        assert_eq!(Algorithm::RSASHA512, Algorithm::from(10));
767        assert_eq!(Algorithm::Reserved(11), Algorithm::from(11));
768        assert_eq!(Algorithm::ECCGOST, Algorithm::from(12));
769        assert_eq!(Algorithm::ECDSAP256SHA256, Algorithm::from(13));
770        assert_eq!(Algorithm::ECDSAP384SHA384, Algorithm::from(14));
771        assert_eq!(Algorithm::ED25519, Algorithm::from(15));
772        assert_eq!(Algorithm::ED448, Algorithm::from(16));
773        assert_eq!(Algorithm::SM2SM3, Algorithm::from(17));
774        assert_eq!(Algorithm::Unassigned(18), Algorithm::from(18));
775        assert_eq!(Algorithm::Unassigned(20), Algorithm::from(20));
776        assert_eq!(Algorithm::ECCGOST12, Algorithm::from(23));
777        assert_eq!(Algorithm::INDIRECT, Algorithm::from(252));
778        assert_eq!(Algorithm::PRIVATEDNS, Algorithm::from(253));
779        assert_eq!(Algorithm::PRIVATEOID, Algorithm::from(254));
780
781        let algorithm_reserved_0 = Algorithm::Reserved(0);
782        let algorithm_reserved_9 = Algorithm::Reserved(9);
783
784        assert_eq!(u8::from(algorithm_reserved_0), 0);
785        assert_eq!(u8::from(Algorithm::DH), 2);
786
787        assert_eq!(u8::from(Algorithm::DSA), 3);
788        assert_eq!(u8::from(Algorithm::ECC), 4);
789        assert_eq!(u8::from(Algorithm::RSASHA1), 5);
790        assert_eq!(u8::from(Algorithm::DSANSEC3SHA1), 6);
791        assert_eq!(u8::from(Algorithm::RSASHA1NSEC3SHA1), 7);
792        assert_eq!(u8::from(Algorithm::RSASHA256), 8);
793        assert_eq!(u8::from(Algorithm::Reserved(9)), 9);
794        assert_eq!(u8::from(Algorithm::RSASHA512), 10);
795        assert_eq!(u8::from(Algorithm::Reserved(11)), 11);
796        assert_eq!(u8::from(Algorithm::ECCGOST), 12);
797        assert_eq!(u8::from(Algorithm::ECDSAP256SHA256), 13);
798        assert_eq!(u8::from(Algorithm::ECDSAP384SHA384), 14);
799        assert_eq!(u8::from(Algorithm::ED25519), 15);
800        assert_eq!(u8::from(Algorithm::ED448), 16);
801        assert_eq!(u8::from(Algorithm::SM2SM3), 17);
802        assert_eq!(u8::from(Algorithm::Unassigned(18)), 18);
803        assert_eq!(u8::from(Algorithm::Unassigned(20)), 20);
804        assert_eq!(u8::from(Algorithm::ECCGOST12), 23);
805        assert_eq!(u8::from(Algorithm::INDIRECT), 252);
806        assert_eq!(u8::from(Algorithm::PRIVATEDNS), 253);
807        assert_eq!(u8::from(Algorithm::PRIVATEOID), 254);
808
809        assert_eq!(u8::from(algorithm_reserved_9), 9);
810    }
811
812    #[test]
813    fn test_valid_cert_data_length() {
814        let valid_cert_data = [1, 2, 3, 4, 5, 6]; // At least 6 bytes
815        let result = CERT::try_from(&valid_cert_data[..]);
816        assert!(
817            result.is_ok(),
818            "Expected a valid result with sufficient cert_data length"
819        );
820    }
821
822    #[test]
823    fn test_cert_creation() {
824        // Sample values
825        let cert_type = CertType::PKIX;
826        let key_tag = 12345;
827        let algorithm = Algorithm::RSASHA256; // Replace with an actual variant from Algorithm
828        let cert_data = [1, 2, 3, 4, 5];
829
830        // Create an instance of the CERT struct
831        let cert = CERT {
832            cert_type,
833            key_tag,
834            algorithm,
835            cert_data: cert_data.to_vec(),
836        };
837
838        // Assert that the fields are correctly set
839        assert_eq!(cert.cert_type, cert_type);
840        assert_eq!(cert.key_tag, key_tag);
841        assert_eq!(cert.algorithm, algorithm);
842        assert_eq!(cert.cert_data, cert_data);
843    }
844
845    #[test]
846    fn test_cert_empty_cert_data() {
847        let cert_type = CertType::PKIX;
848        let key_tag = 12345;
849        let algorithm = Algorithm::RSASHA256;
850        let cert_data = Vec::new(); // Empty cert_data
851
852        // Create an instance of the CERT struct
853        let cert = CERT {
854            cert_type,
855            key_tag,
856            algorithm,
857            cert_data,
858        };
859
860        // Assert that cert_data is empty and other fields are correctly set
861        assert_eq!(cert.cert_type, cert_type);
862        assert_eq!(cert.key_tag, key_tag);
863        assert_eq!(cert.algorithm, algorithm);
864        assert!(cert.cert_data.is_empty());
865    }
866
867    #[test]
868    fn test_valid_cert_record() {
869        // Create a mock cert_data with 5 initial bytes + valid Base64 string for the rest
870        let valid_cert_record = [
871            0x00, 0x01, // cert_type: 1 (PKIX)
872            0x30, 0x39, // key_tag: 12345
873            0x08, // algorithm: 8 (e.g., RSASHA256)
874            65, 81, 73, 68, // "AQID" = [1, 2, 3]
875        ];
876
877        let cert = CERT::try_from(&valid_cert_record[..]);
878        assert!(cert.is_ok(), "Expected valid cert_record");
879
880        let cert = cert.unwrap();
881        assert_eq!(cert.cert_type, CertType::PKIX);
882        assert_eq!(cert.key_tag, 12345);
883        assert_eq!(cert.algorithm, Algorithm::RSASHA256); // Assuming this is algorithm 8
884        assert_eq!(cert.cert_data, [65, 81, 73, 68]);
885    }
886
887    #[test]
888    fn test_invalid_cert_record_length() {
889        let invalid_cert_record = [1, 2, 3, 4]; // Less than 5 bytes
890
891        let result = CERT::try_from(&invalid_cert_record[..]);
892        assert!(
893            matches!(
894                result,
895                Err(DecodeError::IncorrectRDataLengthRead { read: 4, len: 6 })
896            ),
897            "Expected error due to invalid cert_record length, got {result:?}"
898        );
899    }
900
901    #[test]
902    fn test_valid_cert_data() {
903        // Base64-encoded dummy certificate data.
904        let tokens = vec!["1", "123", "3", "Q2VydGlmaWNhdGUgZGF0YQ=="].into_iter();
905
906        let result = CERT::from_tokens(tokens);
907
908        assert!(result.is_ok());
909
910        let cert = result.unwrap();
911        assert_eq!(cert.cert_type, CertType::from(1));
912        assert_eq!(cert.key_tag, 123);
913        assert_eq!(cert.algorithm, Algorithm::from(3));
914        assert_eq!(cert.cert_data, b"Certificate data".to_vec()); // Decoded base64 data.
915    }
916
917    #[test]
918    fn test_invalid_base64_data() {
919        // Invalid base64 data (contains invalid characters).
920        let tokens = vec!["1", "123", "3", "Invalid_base64"].into_iter();
921
922        let result = CERT::from_tokens(tokens);
923
924        // Expecting an error for invalid base64 data.
925        assert!(result.is_err());
926        let err = result.unwrap_err();
927        assert_eq!(format!("{err}"), "Invalid base64 CERT data");
928    }
929
930    #[test]
931    fn test_invalid_token_digit() {
932        // Missing cert_type (first token) will try to decode cert leading to invalid digit
933        let tokens = vec!["123", "3", "Q2VydGlmaWNhdGUgZGF0YQ=="].into_iter();
934
935        let result = CERT::from_tokens(tokens);
936
937        // Expecting an error due to missing cert type.
938        assert!(result.is_err());
939        let err = result.unwrap_err();
940        assert_eq!(format!("{err}"), "Invalid digit found in algorithm token");
941    }
942
943    #[test]
944    fn test_missing_cert_data() {
945        // Missing cert_data (last token)
946        let tokens = vec!["1", "123", "3"].into_iter();
947
948        let result = CERT::from_tokens(tokens);
949
950        // Expecting an error due to missing cert data.
951        assert!(result.is_err());
952        let err = result.unwrap_err();
953        assert_eq!(format!("{err}"), "CERT data missing");
954    }
955
956    #[test]
957    fn test_mnemonics_and_split_data() {
958        let tokens = ["pgp", "7", "rsasha1", "Q2VydGlm", "aWNhdGUgZGF0YQ=="].into_iter();
959        let cert = CERT::from_tokens(tokens).unwrap();
960        assert_eq!(cert.cert_type, CertType::PGP);
961        assert_eq!(cert.algorithm, Algorithm::RSASHA1);
962        assert_eq!(cert.cert_data, b"Certificate data".to_vec());
963    }
964
965    #[test]
966    fn test_display_round_trip() {
967        for (cert_type, algorithm, expected) in [
968            (0, 0, "0 1 0 AQID"),
969            (1, 8, "PKIX 1 RSASHA256 AQID"),
970            (6, 6, "IPGP 1 6 AQID"),
971            (9, 20, "9 1 20 AQID"),
972            (253, 13, "URI 1 ECDSAP256SHA256 AQID"),
973            (255, 252, "255 1 INDIRECT AQID"),
974            (65280, 255, "65280 1 255 AQID"),
975            (65535, 23, "65535 1 23 AQID"),
976        ] {
977            let cert = CERT::new(
978                CertType::from(cert_type),
979                1,
980                Algorithm::from(algorithm),
981                vec![1, 2, 3],
982            );
983            let text = cert.to_string();
984            assert_eq!(text, expected);
985            assert_eq!(CERT::from_tokens(text.split(' ')).unwrap(), cert);
986        }
987    }
988}