Add support for CNAME resource records
[dnssec-prover] / src / lib.rs
1 //! The DNS provides a single, global, hierarchical namespace with (when DNSSEC is used)
2 //! cryptographic guarantees on all of its data.
3 //!
4 //! This makes it incredibly powerful for resolving human-readable names into arbitrary, secured
5 //! data.
6 //!
7 //! Unlike TLS, this cryptographic security provides transferable proofs which can convince an
8 //! offline device, using simple cryptographic primitives and a single root trusted key, of the
9 //! validity of DNS data.
10 //!
11 //! This crate implements the creation and validation of such proofs, using the format from RFC
12 //! 9102 to create transferable proofs of DNS entries.
13 //!
14 //! It is no-std (but requires `alloc`) and seeks to have minimal dependencies and a reasonably
15 //! conservative MSRV policy, allowing it to be used in as many places as possible.
16
17 #![allow(deprecated)] // XXX
18 #![deny(missing_docs)]
19
20 #![no_std]
21 extern crate alloc;
22
23 use alloc::vec::Vec;
24 use alloc::vec;
25 use alloc::string::String;
26 use alloc::borrow::ToOwned;
27
28 use ring::signature;
29
30 /// Gets the trusted root anchors
31 ///
32 /// These are available at <https://data.iana.org/root-anchors/root-anchors.xml>
33 pub fn root_hints() -> Vec<DS> {
34         #[allow(unused_mut)]
35         let mut res = vec![DS {
36                 name: ".".try_into().unwrap(), key_tag: 19036, alg: 8, digest_type: 2,
37                 digest: hex_lit::hex!("49AAC11D7B6F6446702E54A1607371607A1A41855200FD2CE1CDDE32F24E8FB5").to_vec(),
38         }, DS {
39                 name: ".".try_into().unwrap(), key_tag: 20326, alg: 8, digest_type: 2,
40                 digest: hex_lit::hex!("E06D44B80B8F1D39A95C0B0D7C65D08458E880409BBC683457104237C7F8EC8D").to_vec(),
41         }];
42         // In tests, add the trust anchor from RFC 9102
43         #[cfg(test)]
44         res.push(DS {
45                 name: ".".try_into().unwrap(), key_tag: 47005, alg: 13, digest_type: 2,
46                 digest: hex_lit::hex!("2eb6e9f2480126691594d649a5a613de3052e37861634641bb568746f2ffc4d4").to_vec(),
47         });
48         res
49 }
50
51 /// A valid domain name.
52 ///
53 /// It must end with a ".", be no longer than 255 bytes, consist of only printable ASCII
54 /// characters and each label may be no longer than 63 bytes.
55 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
56 pub struct Name(String);
57 impl core::ops::Deref for Name {
58         type Target = str;
59         fn deref(&self) -> &str { &self.0 }
60 }
61 impl TryFrom<String> for Name {
62         type Error = ();
63         fn try_from(s: String) -> Result<Name, ()> {
64                 if s.is_empty() { return Err(()); }
65                 if *s.as_bytes().last().unwrap_or(&0) != b"."[0] { return Err(()); }
66                 if s.len() > 255 { return Err(()); }
67                 if s.chars().any(|c| !c.is_ascii_graphic() && c != '.' && c != '-') { return Err(()); }
68                 for label in s.split(".") {
69                         if label.len() > 63 { return Err(()); }
70                 }
71
72                 Ok(Name(s))
73         }
74 }
75 impl TryFrom<&str> for Name {
76         type Error = ();
77         fn try_from(s: &str) -> Result<Name, ()> {
78                 Self::try_from(s.to_owned())
79         }
80 }
81
82 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
83 /// A supported Resource Record
84 ///
85 /// Note that we only currently support a handful of RR types as needed to generate and validate
86 /// TXT or TLSA record proofs.
87 pub enum RR {
88         /// A text resource record
89         Txt(Txt),
90         /// A TLS Certificate Association resource record
91         TLSA(TLSA),
92         /// A Canonical Name record
93         CName(CName),
94         /// A DNS (Public) Key resource record
95         DnsKey(DnsKey),
96         /// A Delegated Signer resource record
97         DS(DS),
98         /// A Resource Record Signature record
99         RRSig(RRSig),
100 }
101 impl RR {
102         /// Gets the name this record refers to.
103         pub fn name(&self) -> &Name {
104                 match self {
105                         RR::Txt(rr) => &rr.name,
106                         RR::CName(rr) => &rr.name,
107                         RR::TLSA(rr) => &rr.name,
108                         RR::DnsKey(rr) => &rr.name,
109                         RR::DS(rr) => &rr.name,
110                         RR::RRSig(rr) => &rr.name,
111                 }
112         }
113         fn ty(&self) -> u16 {
114                 match self {
115                         RR::Txt(_) => Txt::TYPE,
116                         RR::CName(_) => CName::TYPE,
117                         RR::TLSA(_) => TLSA::TYPE,
118                         RR::DnsKey(_) => DnsKey::TYPE,
119                         RR::DS(_) => DS::TYPE,
120                         RR::RRSig(_) => RRSig::TYPE,
121                 }
122         }
123         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
124                 match self {
125                         RR::Txt(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
126                         RR::CName(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
127                         RR::TLSA(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
128                         RR::DnsKey(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
129                         RR::DS(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
130                         RR::RRSig(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
131                 }
132         }
133 }
134 impl From<Txt> for RR { fn from(txt: Txt) -> RR { RR::Txt(txt) } }
135 impl From<CName> for RR { fn from(cname: CName) -> RR { RR::CName(cname) } }
136 impl From<TLSA> for RR { fn from(tlsa: TLSA) -> RR { RR::TLSA(tlsa) } }
137 impl From<DnsKey> for RR { fn from(dnskey: DnsKey) -> RR { RR::DnsKey(dnskey) } }
138 impl From<DS> for RR { fn from(ds: DS) -> RR { RR::DS(ds) } }
139 impl From<RRSig> for RR { fn from(rrsig: RRSig) -> RR { RR::RRSig(rrsig) } }
140
141 trait StaticRecord : Ord {
142         // http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4
143         const TYPE: u16;
144         fn name(&self) -> &Name;
145         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>);
146 }
147 /// A trait describing a resource record (including the [`RR`] enum).
148 pub trait Record : Ord + {
149         /// The resource record type, as maintained by IANA.
150         ///
151         /// Current assignments can be found at
152         /// <http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4>
153         fn ty(&self) -> u16;
154         /// The name this record is at.
155         fn name(&self) -> &Name;
156         /// Writes the data of this record, prefixed by a u16 length, to the given `Vec`.
157         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>);
158 }
159 impl<RR: StaticRecord> Record for RR {
160         fn ty(&self) -> u16 { RR::TYPE }
161         fn name(&self) -> &Name { RR::name(self) }
162         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
163                 RR::write_u16_len_prefixed_data(self, out)
164         }
165 }
166 impl Record for RR {
167         fn ty(&self) -> u16 { self.ty() }
168         fn name(&self) -> &Name { self.name() }
169         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
170                 self.write_u16_len_prefixed_data(out)
171         }
172 }
173
174 fn read_u8(inp: &mut &[u8]) -> Result<u8, ()> {
175         let res = *inp.get(0).ok_or(())?;
176         *inp = &inp[1..];
177         Ok(res)
178 }
179 fn read_u16(inp: &mut &[u8]) -> Result<u16, ()> {
180         if inp.len() < 2 { return Err(()); }
181         let mut bytes = [0; 2];
182         bytes.copy_from_slice(&inp[..2]);
183         *inp = &inp[2..];
184         Ok(u16::from_be_bytes(bytes))
185 }
186 fn read_u32(inp: &mut &[u8]) -> Result<u32, ()> {
187         if inp.len() < 4 { return Err(()); }
188         let mut bytes = [0; 4];
189         bytes.copy_from_slice(&inp[..4]);
190         *inp = &inp[4..];
191         Ok(u32::from_be_bytes(bytes))
192 }
193
194 fn read_name(inp: &mut &[u8]) -> Result<Name, ()> {
195         let mut name = String::with_capacity(1024);
196         loop {
197                 let len = read_u8(inp)? as usize;
198                 if len == 0 {
199                         if name.is_empty() { name += "."; }
200                         break;
201                 }
202                 if inp.len() <= len { return Err(()); }
203                 name += core::str::from_utf8(&inp[..len]).map_err(|_| ())?;
204                 name += ".";
205                 *inp = &inp[len..];
206                 if name.len() > 1024 { return Err(()); }
207         }
208         Ok(name.try_into()?)
209 }
210
211 trait Writer { fn write(&mut self, buf: &[u8]); }
212 impl Writer for Vec<u8> { fn write(&mut self, buf: &[u8]) { self.extend_from_slice(buf); } }
213 impl Writer for ring::digest::Context { fn write(&mut self, buf: &[u8]) { self.update(buf); } }
214 fn write_name<W: Writer>(out: &mut W, name: &str) {
215         let canonical_name = name.to_ascii_lowercase();
216         if canonical_name == "." {
217                 out.write(&[0]);
218         } else {
219                 for label in canonical_name.split(".") {
220                         out.write(&(label.len() as u8).to_be_bytes());
221                         out.write(label.as_bytes());
222                 }
223         }
224 }
225 fn name_len(name: &Name) -> u16 {
226         if name.0 == "." {
227                 1
228         } else {
229                 let mut res = 0;
230                 for label in name.split(".") {
231                         res += 1 + label.len();
232                 }
233                 res as u16
234         }
235 }
236
237 fn parse_rr(inp: &mut &[u8]) -> Result<RR, ()> {
238         let name = read_name(inp)?;
239         let ty = read_u16(inp)?;
240         let class = read_u16(inp)?;
241         if class != 1 { return Err(()); } // We only support the INternet
242         let _ttl = read_u32(inp)?;
243         let data_len = read_u16(inp)? as usize;
244         if inp.len() < data_len { return Err(()); }
245         let mut data = &inp[..data_len];
246         *inp = &inp[data_len..];
247
248         match ty {
249                 Txt::TYPE => {
250                         let mut parsed_data = Vec::with_capacity(data_len - 1);
251                         while !data.is_empty() {
252                                 let len = read_u8(&mut data)? as usize;
253                                 if data.len() < len { return Err(()); }
254                                 parsed_data.extend_from_slice(&data[..len]);
255                                 data = &data[len..];
256                         }
257                         Ok(RR::Txt(Txt { name, data: parsed_data }))
258                 }
259                 CName::TYPE => {
260                         Ok(RR::CName(CName { name, canonical_name: read_name(&mut data)? }))
261                 }
262                 TLSA::TYPE => {
263                         if data_len <= 3 { return Err(()); }
264                         Ok(RR::TLSA(TLSA {
265                                 name, cert_usage: read_u8(&mut data)?, selector: read_u8(&mut data)?,
266                                 data_ty: read_u8(&mut data)?, data: data.to_vec(),
267                         }))
268                 },
269                 DnsKey::TYPE => {
270                         Ok(RR::DnsKey(DnsKey {
271                                 name, flags: read_u16(&mut data)?, protocol: read_u8(&mut data)?,
272                                 alg: read_u8(&mut data)?, pubkey: data.to_vec(),
273                         }))
274                 },
275                 DS::TYPE => {
276                         Ok(RR::DS(DS {
277                                 name, key_tag: read_u16(&mut data)?, alg: read_u8(&mut data)?,
278                                 digest_type: read_u8(&mut data)?, digest: data.to_vec(),
279                         }))
280                 },
281                 RRSig::TYPE => {
282                         Ok(RR::RRSig(RRSig {
283                                 name, ty: read_u16(&mut data)?, alg: read_u8(&mut data)?,
284                                 labels: read_u8(&mut data)?, orig_ttl: read_u32(&mut data)?,
285                                 expiration: read_u32(&mut data)?, inception: read_u32(&mut data)?,
286                                 key_tag: read_u16(&mut data)?, key_name: read_name(&mut data)?,
287                                 signature: data.to_vec(),
288                         }))
289                 },
290                 _ => Err(()),
291         }
292 }
293 /// Parse a stream of [`RR`]s from the format described in [RFC 9102](https://www.rfc-editor.org/rfc/rfc9102.html).
294 ///
295 /// Note that this is only the series of `AuthenticationChain` records, and does not read the
296 /// `ExtSupportLifetime` field at the start of a `DnssecChainExtension`.
297 pub fn parse_rr_stream(mut inp: &[u8]) -> Result<Vec<RR>, ()> {
298         let mut res = Vec::with_capacity(32);
299         while !inp.is_empty() {
300                 res.push(parse_rr(&mut inp)?);
301         }
302         Ok(res)
303 }
304
305 /// Writes the given resource record in its wire encoding to the given `Vec`.
306 ///
307 /// An [RFC 9102](https://www.rfc-editor.org/rfc/rfc9102.html) `AuthenticationChain` is simply a
308 /// series of such records with no additional bytes in between.
309 pub fn write_rr<RR: Record>(rr: &RR, ttl: u32, out: &mut Vec<u8>) {
310         write_name(out, rr.name());
311         out.extend_from_slice(&rr.ty().to_be_bytes());
312         out.extend_from_slice(&1u16.to_be_bytes()); // The INternet class
313         out.extend_from_slice(&ttl.to_be_bytes());
314         rr.write_u16_len_prefixed_data(out);
315 }
316
317 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] // TODO: ord is wrong cause need to consider len first, maybe
318 /// A text resource record, containing arbitrary text data
319 pub struct Txt {
320         /// The name this record is at.
321         pub name: Name,
322         /// The text record itself.
323         ///
324         /// While this is generally UTF-8-valid, there is no specific requirement that it be, and thus
325         /// is an arbitrary series of bytes here.
326         data: Vec<u8>,
327 }
328 impl StaticRecord for Txt {
329         const TYPE: u16 = 16;
330         fn name(&self) -> &Name { &self.name }
331         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
332                 let len = (self.data.len() + self.data.len() / 255 + 1) as u16;
333                 out.extend_from_slice(&len.to_be_bytes());
334
335                 let mut data_write = &self.data[..];
336                 out.extend_from_slice(&[data_write.len().try_into().unwrap_or(255)]);
337                 while !data_write.is_empty() {
338                         let split_pos = core::cmp::min(255, data_write.len());
339                         out.extend_from_slice(&data_write[..split_pos]);
340                         data_write = &data_write[split_pos..];
341                         if !data_write.is_empty() {
342                                 out.extend_from_slice(&[data_write.len().try_into().unwrap_or(255)]);
343                         }
344                 }
345         }
346 }
347
348 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
349 /// A TLS Certificate Association resource record containing information about the TLS certificate
350 /// which should be expected when communicating with the host at the given name.
351 ///
352 /// See <https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities#TLSA_RR> for more
353 /// info.
354 pub struct TLSA {
355         /// The name this record is at.
356         pub name: Name,
357         /// The type of constraint on the TLS certificate(s) used which should be enforced by this
358         /// record.
359         pub cert_usage: u8,
360         /// Whether to match on the full certificate, or only the public key.
361         pub selector: u8,
362         /// The type of data included which is used to match the TLS certificate(s).
363         pub data_ty: u8,
364         /// The certificate data or hash of the certificate data itself.
365         pub data: Vec<u8>,
366 }
367 impl StaticRecord for TLSA {
368         const TYPE: u16 = 52;
369         fn name(&self) -> &Name { &self.name }
370         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
371                 let len = 3 + self.data.len();
372                 out.extend_from_slice(&(len as u16).to_be_bytes());
373                 out.extend_from_slice(&[self.cert_usage, self.selector, self.data_ty]);
374                 out.extend_from_slice(&self.data);
375         }
376 }
377
378 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
379 /// A Canonical Name resource record, referring all queries for this name to another name.
380 pub struct CName {
381         /// The name this record is at.
382         pub name: Name,
383         /// The canonical name.
384         ///
385         /// A resolver should use this name when looking up any further records for [`Self::name`].
386         pub canonical_name: Name,
387 }
388 impl StaticRecord for CName {
389         const TYPE: u16 = 5;
390         fn name(&self) -> &Name { &self.name }
391         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
392                 let len: u16 = name_len(&self.canonical_name);
393                 out.extend_from_slice(&len.to_be_bytes());
394                 write_name(out, &self.canonical_name);
395         }
396 }
397
398 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
399 /// A public key resource record which can be used to validate [`RRSig`]s.
400 pub struct DnsKey {
401         /// The name this record is at.
402         pub name: Name,
403         /// Flags which constrain the usage of this public key.
404         pub flags: u16,
405         /// The protocol this key is used for (protocol `3` is DNSSEC). 
406         pub protocol: u8,
407         /// The algorithm which this public key uses to sign data.
408         pub alg: u8,
409         /// The public key itself.
410         pub pubkey: Vec<u8>,
411 }
412 impl StaticRecord for DnsKey {
413         const TYPE: u16 = 48;
414         fn name(&self) -> &Name { &self.name }
415         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
416                 let len = 2 + 1 + 1 + self.pubkey.len();
417                 out.extend_from_slice(&(len as u16).to_be_bytes());
418                 out.extend_from_slice(&self.flags.to_be_bytes());
419                 out.extend_from_slice(&self.protocol.to_be_bytes());
420                 out.extend_from_slice(&self.alg.to_be_bytes());
421                 out.extend_from_slice(&self.pubkey);
422         }
423 }
424 impl DnsKey {
425         /// A short (non-cryptographic) digest which can be used to refer to this [`DnsKey`].
426         pub fn key_tag(&self) -> u16 {
427                 let mut res = u32::from(self.flags);
428                 res += u32::from(self.protocol) << 8;
429                 res += u32::from(self.alg);
430                 for (idx, b) in self.pubkey.iter().enumerate() {
431                         if idx % 2 == 0 {
432                                 res += u32::from(*b) << 8;
433                         } else {
434                                 res += u32::from(*b);
435                         }
436                 }
437                 res += (res >> 16) & 0xffff;
438                 (res & 0xffff) as u16
439         }
440 }
441
442 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
443 /// A Delegation Signer resource record which indicates that some alternative [`DnsKey`] can sign
444 /// for records in the zone which matches [`DS::name`].
445 pub struct DS {
446         /// The name this record is at.
447         ///
448         /// This is also the zone that a [`DnsKey`] which matches the [`Self::digest`] can sign for.
449         pub name: Name,
450         /// A short tag which describes the matching [`DnsKey`].
451         ///
452         /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which is referred to by this
453         /// [`DS`].
454         pub key_tag: u16,
455         /// The algorithm which the [`DnsKey`] referred to by this [`DS`] uses.
456         ///
457         /// This matches the [`DnsKey::alg`] field in the referred-to [`DnsKey`].
458         pub alg: u8,
459         /// The type of digest used to hash the referred-to [`DnsKey`].
460         pub digest_type: u8,
461         /// The digest itself.
462         pub digest: Vec<u8>,
463 }
464 impl StaticRecord for DS {
465         const TYPE: u16 = 43;
466         fn name(&self) -> &Name { &self.name }
467         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
468                 let len = 2 + 1 + 1 + self.digest.len();
469                 out.extend_from_slice(&(len as u16).to_be_bytes());
470                 out.extend_from_slice(&self.key_tag.to_be_bytes());
471                 out.extend_from_slice(&self.alg.to_be_bytes());
472                 out.extend_from_slice(&self.digest_type.to_be_bytes());
473                 out.extend_from_slice(&self.digest);
474         }
475 }
476
477 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
478 /// A Resource Record (set) Signature resource record. This contains a signature over all the
479 /// resources records of the given type at the given name.
480 pub struct RRSig {
481         /// The name this record is at.
482         ///
483         /// This is also the name of any records which this signature is covering (ignoring wildcards).
484         pub name: Name,
485         /// The resource record type which this [`RRSig`] is signing.
486         ///
487         /// All resources records of this type at the same name as [`Self::name`] must be signed by
488         /// this [`RRSig`].
489         pub ty: u16,
490         /// The algorithm which is being used to sign.
491         ///
492         /// This must match the [`DnsKey::alg`] field in the [`DnsKey`] being used to sign.
493         pub alg: u8,
494         /// The number of labels in the name of the records that this signature is signing.
495         // TODO: Describe this better in terms of wildcards
496         pub labels: u8,
497         /// The TTL of the records which this [`RRSig`] is signing.
498         pub orig_ttl: u32,
499         /// The expiration (as a UNIX timestamp) of this signature.
500         pub expiration: u32,
501         /// The time (as a UNIX timestamp) at which this signature becomes valid.
502         pub inception: u32,
503         /// A short tag which describes the matching [`DnsKey`].
504         ///
505         /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which created this signature.
506         pub key_tag: u16,
507         /// The [`DnsKey::name`] in the [`DnsKey`] which created this signature.
508         ///
509         /// This must be a parent of the [`Self::name`].
510         pub key_name: Name,
511         /// The signature itself.
512         pub signature: Vec<u8>,
513 }
514 impl StaticRecord for RRSig {
515         const TYPE: u16 = 46;
516         fn name(&self) -> &Name { &self.name }
517         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
518                 let len = 2 + 1 + 1 + 4*3 + 2 + name_len(&self.key_name) + self.signature.len() as u16;
519                 out.extend_from_slice(&len.to_be_bytes());
520                 out.extend_from_slice(&self.ty.to_be_bytes());
521                 out.extend_from_slice(&self.alg.to_be_bytes());
522                 out.extend_from_slice(&self.labels.to_be_bytes());
523                 out.extend_from_slice(&self.orig_ttl.to_be_bytes());
524                 out.extend_from_slice(&self.expiration.to_be_bytes());
525                 out.extend_from_slice(&self.inception.to_be_bytes());
526                 out.extend_from_slice(&self.key_tag.to_be_bytes());
527                 write_name(out, &self.key_name);
528                 out.extend_from_slice(&self.signature);
529         }
530 }
531
532 #[derive(Debug, PartialEq)]
533 /// An error when validating DNSSEC signatures or other data
534 pub enum ValidationError {
535         /// An algorithm used in signing was not supported.
536         ///
537         /// In general DNS usage the resulting data should be used anyway, as we were able to verify
538         /// that a zone wished to use the unsupported algorithm.
539         ///
540         /// However, in cases where signing is mandatory, this can be treated as an error.
541         UnsupportedAlgorithm,
542         /// The provided data was invalid or signatures did not validate.
543         Invalid,
544 }
545
546 fn bytes_to_rsa_pk<'a>(pubkey: &'a [u8])
547 -> Result<signature::RsaPublicKeyComponents<&'a [u8]>, ValidationError> {
548         if pubkey.len() <= 3 { return Err(ValidationError::Invalid); }
549
550         let mut pos = 0;
551         let exponent_length;
552         if pubkey[0] == 0 {
553                 exponent_length = ((pubkey[1] as usize) << 8) | (pubkey[2] as usize);
554                 pos += 3;
555         } else {
556                 exponent_length = pubkey[0] as usize;
557                 pos += 1;
558         }
559
560         if pubkey.len() <= pos + exponent_length { return Err(ValidationError::Invalid); }
561         Ok(signature::RsaPublicKeyComponents {
562                 n: &pubkey[pos + exponent_length..],
563                 e: &pubkey[pos..pos + exponent_length]
564         })
565 }
566
567 // TODO: return the validity period
568 fn verify_rrsig<'a, RR: Record, Keys>(sig: &RRSig, dnskeys: Keys, mut records: Vec<&RR>)
569 -> Result<(), ValidationError>
570 where Keys: IntoIterator<Item = &'a DnsKey> {
571         for record in records.iter() {
572                 if sig.ty != record.ty() { return Err(ValidationError::Invalid); }
573         }
574         for dnskey in dnskeys.into_iter() {
575                 if dnskey.key_tag() == sig.key_tag {
576                         // Protocol must be 3, otherwise its not DNSSEC
577                         if dnskey.protocol != 3 { continue; }
578                         // The ZONE flag must be set if we're going to validate RRs with this key.
579                         if dnskey.flags & 0b1_0000_0000 == 0 { continue; }
580                         if dnskey.alg != sig.alg { continue; }
581
582                         // TODO: Check orig_ttl somehow?
583
584                         let mut signed_data = Vec::with_capacity(2048);
585                         signed_data.extend_from_slice(&sig.ty.to_be_bytes());
586                         signed_data.extend_from_slice(&sig.alg.to_be_bytes());
587                         signed_data.extend_from_slice(&sig.labels.to_be_bytes()); // Check this somehow?
588                         signed_data.extend_from_slice(&sig.orig_ttl.to_be_bytes());
589                         signed_data.extend_from_slice(&sig.expiration.to_be_bytes()); // Return this and inception
590                         signed_data.extend_from_slice(&sig.inception.to_be_bytes());
591                         signed_data.extend_from_slice(&sig.key_tag.to_be_bytes());
592                         write_name(&mut signed_data, &sig.key_name);
593
594                         records.sort();
595
596                         for record in records.iter() {
597                                 // TODO: Handle wildcards
598                                 write_name(&mut signed_data, record.name());
599                                 signed_data.extend_from_slice(&record.ty().to_be_bytes());
600                                 signed_data.extend_from_slice(&1u16.to_be_bytes()); // The INternet class
601                                 signed_data.extend_from_slice(&sig.orig_ttl.to_be_bytes());
602                                 record.write_u16_len_prefixed_data(&mut signed_data);
603                         }
604
605                         match sig.alg {
606                                 8|10 => {
607                                         let alg = if sig.alg == 8 {
608                                                 &signature::RSA_PKCS1_1024_8192_SHA256_FOR_LEGACY_USE_ONLY
609                                         } else {
610                                                 &signature::RSA_PKCS1_1024_8192_SHA512_FOR_LEGACY_USE_ONLY
611                                         };
612                                         bytes_to_rsa_pk(&dnskey.pubkey)?
613                                                 .verify(alg, &signed_data, &sig.signature)
614                                                 .map_err(|_| ValidationError::Invalid)?;
615                                 },
616                                 13|14 => {
617                                         let alg = if sig.alg == 13 {
618                                                 &signature::ECDSA_P256_SHA256_FIXED
619                                         } else {
620                                                 &signature::ECDSA_P384_SHA384_FIXED
621                                         };
622
623                                         // Add 0x4 identifier to the ECDSA pubkey as expected by ring.
624                                         let mut key = Vec::with_capacity(dnskey.pubkey.len() + 1);
625                                         key.push(0x4);
626                                         key.extend_from_slice(&dnskey.pubkey);
627
628                                         signature::UnparsedPublicKey::new(alg, &key)
629                                                 .verify(&signed_data, &sig.signature)
630                                                 .map_err(|_| ValidationError::Invalid)?;
631                                 },
632                                 15 => {
633                                         signature::UnparsedPublicKey::new(&signature::ED25519, &dnskey.pubkey)
634                                                 .verify(&signed_data, &sig.signature)
635                                                 .map_err(|_| ValidationError::Invalid)?;
636                                 },
637                                 _ => return Err(ValidationError::UnsupportedAlgorithm),
638                         }
639
640                         return Ok(());
641                 }
642         }
643         Err(ValidationError::Invalid)
644 }
645
646 fn verify_dnskey_rrsig<'a, T, I>(sig: &RRSig, dses: T, records: Vec<&DnsKey>)
647 -> Result<(), ValidationError>
648 where T: IntoIterator<IntoIter = I>, I: Iterator<Item = &'a DS> + Clone {
649         let mut validated_dnskeys = Vec::with_capacity(records.len());
650         let dses = dses.into_iter();
651
652         let mut had_known_digest_type = false;
653         let mut had_ds = false;
654         for ds in dses.clone() {
655                 had_ds = true;
656                 if ds.digest_type == 2 || ds.digest_type == 4 {
657                         had_known_digest_type = true;
658                         break;
659                 }
660         }
661         if !had_ds { return Err(ValidationError::Invalid); }
662         if !had_known_digest_type { return Err(ValidationError::UnsupportedAlgorithm); }
663
664         for dnskey in records.iter() {
665                 for ds in dses.clone() {
666                         if ds.digest_type != 2 && ds.digest_type != 4 { continue; }
667                         if ds.alg != dnskey.alg { continue; }
668                         if dnskey.key_tag() == ds.key_tag {
669                                 let alg = match ds.digest_type {
670                                         2 => &ring::digest::SHA256,
671                                         4 => &ring::digest::SHA384,
672                                         _ => continue,
673                                 };
674                                 let mut ctx = ring::digest::Context::new(alg);
675                                 write_name(&mut ctx, &dnskey.name);
676                                 ctx.update(&dnskey.flags.to_be_bytes());
677                                 ctx.update(&dnskey.protocol.to_be_bytes());
678                                 ctx.update(&dnskey.alg.to_be_bytes());
679                                 ctx.update(&dnskey.pubkey);
680                                 let hash = ctx.finish();
681                                 if hash.as_ref() == &ds.digest {
682                                         validated_dnskeys.push(*dnskey);
683                                         break;
684                                 }
685                         }
686                 }
687         }
688         verify_rrsig(sig, validated_dnskeys.iter().map(|k| *k), records)
689 }
690
691 /// Verifies the given set of resource records.
692 ///
693 /// Given a set of arbitrary records, this attempts to validate DNSSEC data from the [`root_hints`]
694 /// through to any supported non-DNSSEC record types.
695 ///
696 /// All records which could be validated are returned, though if an error is found validating any
697 /// contained record, only `Err` will be returned.
698 pub fn verify_rr_stream<'a>(inp: &'a [RR]) -> Result<Vec<&'a RR>, ValidationError> {
699         let mut zone = ".";
700         let mut res = Vec::new();
701         let mut pending_ds_sets = Vec::with_capacity(1);
702         'next_zone: while zone == "." || !pending_ds_sets.is_empty() {
703                 let mut found_unsupported_alg = false;
704                 let next_ds_set;
705                 if let Some((next_zone, ds_set)) = pending_ds_sets.pop() {
706                         next_ds_set = Some(ds_set);
707                         zone = next_zone;
708                 } else {
709                         debug_assert_eq!(zone, ".");
710                         next_ds_set = None;
711                 }
712
713                 for rrsig in inp.iter()
714                         .filter_map(|rr| if let RR::RRSig(sig) = rr { Some(sig) } else { None })
715                         .filter(|rrsig| rrsig.name.0 == zone && rrsig.ty == DnsKey::TYPE)
716                 {
717                         let dnskeys = inp.iter()
718                                 .filter_map(|rr| if let RR::DnsKey(dnskey) = rr { Some(dnskey) } else { None })
719                                 .filter(move |dnskey| dnskey.name.0 == zone);
720                         let dnskeys_verified = if zone == "." {
721                                 verify_dnskey_rrsig(rrsig, &root_hints(), dnskeys.clone().collect())
722                         } else {
723                                 debug_assert!(next_ds_set.is_some());
724                                 if next_ds_set.is_none() { break 'next_zone; }
725                                 verify_dnskey_rrsig(rrsig, next_ds_set.clone().unwrap(), dnskeys.clone().collect())
726                         };
727                         if dnskeys_verified.is_ok() {
728                                 for rrsig in inp.iter()
729                                         .filter_map(|rr| if let RR::RRSig(sig) = rr { Some(sig) } else { None })
730                                         .filter(move |rrsig| rrsig.key_name.0 == zone && rrsig.name.0 != zone)
731                                 {
732                                         if !rrsig.name.ends_with(zone) { return Err(ValidationError::Invalid); }
733                                         let signed_records = inp.iter()
734                                                 .filter(|rr| rr.name() == &rrsig.name && rr.ty() == rrsig.ty);
735                                         verify_rrsig(rrsig, dnskeys.clone(), signed_records.clone().collect())?;
736                                         match rrsig.ty {
737                                                 // RRSigs shouldn't cover child `DnsKey`s or other `RRSig`s
738                                                 RRSig::TYPE|DnsKey::TYPE => return Err(ValidationError::Invalid),
739                                                 DS::TYPE => {
740                                                         if !pending_ds_sets.iter().any(|(pending_zone, _)| pending_zone == &rrsig.name.0) {
741                                                                 pending_ds_sets.push((
742                                                                         &rrsig.name,
743                                                                         signed_records.filter_map(|rr|
744                                                                                 if let RR::DS(ds) = rr { Some(ds) }
745                                                                                 else { debug_assert!(false, "We already filtered by type"); None })
746                                                                 ));
747                                                         }
748                                                 },
749                                                 _ => {
750                                                         for record in signed_records {
751                                                                 if !res.contains(&record) { res.push(record); }
752                                                         }
753                                                 },
754                                         }
755                                 }
756                                 continue 'next_zone;
757                         } else if dnskeys_verified == Err(ValidationError::UnsupportedAlgorithm) {
758                                 // There may be redundant signatures by different keys, where one we don't supprt
759                                 // and another we do. Ignore ones we don't support, but if there are no more,
760                                 // return UnsupportedAlgorithm
761                                 found_unsupported_alg = true;
762                         } else {
763                                 // We don't explicitly handle invalid signatures here, instead we move on to the
764                                 // next RRSig (if there is one) and return `Invalid` if no `RRSig`s match.
765                         }
766                 }
767                 // No RRSigs were able to verify our DnsKey set
768                 if found_unsupported_alg {
769                         return Err(ValidationError::UnsupportedAlgorithm);
770                 } else {
771                         return Err(ValidationError::Invalid);
772                 }
773         }
774         if res.is_empty() { Err(ValidationError::Invalid) }
775         else { Ok(res) }
776 }
777
778 #[cfg(test)]
779 mod tests {
780         use super::*;
781
782         use hex_conservative::FromHex;
783         use rand::seq::SliceRandom;
784
785         fn root_dnskey() -> (Vec<DnsKey>, Vec<RR>) {
786                 let dnskeys = vec![DnsKey {
787                         name: ".".try_into().unwrap(), flags: 256, protocol: 3, alg: 8,
788                         pubkey: base64::decode("AwEAAentCcIEndLh2QSK+pHFq/PkKCwioxt75d7qNOUuTPMo0Fcte/NbwDPbocvbZ/eNb5RV/xQdapaJASQ/oDLsqzD0H1+JkHNuuKc2JLtpMxg4glSE4CnRXT2CnFTW5IwOREL+zeqZHy68OXy5ngW5KALbevRYRg/q2qFezRtCSQ0knmyPwgFsghVYLKwi116oxwEU5yZ6W7npWMxt5Z+Qs8diPNWrS5aXLgJtrWUGIIuFfuZwXYziGRP/z3o1EfMo9zZU19KLopkoLXX7Ls/diCXdSEdJXTtFA8w0/OKQviuJebfKscoElCTswukVZ1VX5gbaFEo2xWhHJ9Uo63wYaTk=").unwrap(),
789                 }, DnsKey {
790                         name: ".".try_into().unwrap(), flags: 257, protocol: 3, alg: 8,
791                         pubkey: base64::decode("AwEAAaz/tAm8yTn4Mfeh5eyI96WSVexTBAvkMgJzkKTOiW1vkIbzxeF3+/4RgWOq7HrxRixHlFlExOLAJr5emLvN7SWXgnLh4+B5xQlNVz8Og8kvArMtNROxVQuCaSnIDdD5LKyWbRd2n9WGe2R8PzgCmr3EgVLrjyBxWezF0jLHwVN8efS3rCj/EWgvIWgb9tarpVUDK/b58Da+sqqls3eNbuv7pr+eoZG+SrDK6nWeL3c6H5Apxz7LjVc1uTIdsIXxuOLYA4/ilBmSVIzuDWfdRUfhHdY6+cn8HFRm+2hM8AnXGXws9555KrUB5qihylGa8subX2Nn6UwNR1AkUTV74bU=").unwrap(),
792                 }];
793                 let dnskey_rrsig = RRSig {
794                         name: ".".try_into().unwrap(), ty: DnsKey::TYPE, alg: 8, labels: 0, orig_ttl: 172800,
795                         expiration: 1708473600, inception: 1706659200, key_tag: 20326, key_name: ".".try_into().unwrap(),
796                         signature: base64::decode("ZO8LbjtwAiVkkBzOnGbiI/3ilGUPmmJpagsLSBVbIZRG6o/8a+hUZpIPTvk5ERZ1rAW4x0YxKAU8qtaHQpKIp3qYA6u97DYytVD7RdtXKHmGYAvR6QbD5eVTkCw1Sz705rJxbwt6+YM5OBweSUAy5Glo6JSQPDQwRDwj/bV2fLRhJbvfsBgxqaXJA0SaE/ceyvK8gB2NIaguTJNrztr2TENrHxi86OKOuHYDHthOW0TFoPfr19qj/P2eEC6dYniTVovUwHT7e+Hqrb05dJF4mI4ZjaIb5mFf8i5RehT1aRlnb3CLiwJ01bEjrRBo3xUn5I3PkCnglHhx3EvkO73OzA==").unwrap(),
797                 };
798                 let root_hints = root_hints();
799                 verify_dnskey_rrsig(&dnskey_rrsig, &root_hints, dnskeys.iter().collect()).unwrap();
800                 let rrs = vec![dnskeys[0].clone().into(), dnskeys[1].clone().into(), dnskey_rrsig.into()];
801                 (dnskeys, rrs)
802         }
803
804         fn com_dnskey() -> (Vec<DnsKey>, Vec<RR>) {
805                 let root_dnskeys = root_dnskey().0;
806                 let mut com_ds = vec![DS {
807                         name: "com.".try_into().unwrap(), key_tag: 19718, alg: 13, digest_type: 2,
808                         digest: Vec::from_hex("8ACBB0CD28F41250A80A491389424D341522D946B0DA0C0291F2D3D771D7805A").unwrap(),
809                 }];
810                 let ds_rrsig = RRSig {
811                         name: "com.".try_into().unwrap(), ty: DS::TYPE, alg: 8, labels: 1, orig_ttl: 86400,
812                         expiration: 1708189200, inception: 1707062400, key_tag: 30903, key_name: ".".try_into().unwrap(),
813                         signature: base64::decode("vwMOBBwqRBdlmGZB+0FKfyMSignEtpYW9sD4TzPW2E+wdbF7O7epR5cmKmvcv0RUJdM0dGC/QmhCfgf/yqw1Xp7TpmPaYzaruW70hjGXZJO2nY3G6stUVe4S7lM2CzHL7nbbpaB5B+iSu6Ua9dZ+nyKrxfB7855HBLCLrHrkMGxWQiEPTallXXS8tEM1Y2XrsuzAQu2vZ2D2ClhFspFbPwwOdw+G6+NsZ8PnIfTkCj6DuKcgbdxjmGaYmw/6hVt9OU3kGCOBaJaEy4LrD8Kwzfu4S7axMwTKP4y4c5Y/E4k/mVAW0cuUtv549HaDfD2V0CvW1bDl6PqRkOiVsqM/lA==").unwrap(),
814                 };
815                 verify_rrsig(&ds_rrsig, &root_dnskeys, com_ds.iter().collect()).unwrap();
816                 let dnskeys = vec![DnsKey {
817                         name: "com.".try_into().unwrap(), flags: 256, protocol: 3, alg: 13,
818                         pubkey: base64::decode("5i9qjJgyH+9MBz7VO269/srLQB/xRRllyUoVq8oLBZshPe4CGzDSFGnXAM3L/QPzB9ULpJuuy7jcxmBZ5Ebo7A==").unwrap(),
819                 }, DnsKey {
820                         name: "com.".try_into().unwrap(), flags: 257, protocol: 3, alg: 13,
821                         pubkey: base64::decode("tx8EZRAd2+K/DJRV0S+hbBzaRPS/G6JVNBitHzqpsGlz8huE61Ms9ANe6NSDLKJtiTBqfTJWDAywEp1FCsEINQ==").unwrap(),
822                 }];
823                 let dnskey_rrsig = RRSig {
824                         name: "com.".try_into().unwrap(), ty: DnsKey::TYPE, alg: 13, labels: 1, orig_ttl: 86400,
825                         expiration: 1707750155, inception: 1706453855, key_tag: 19718, key_name: "com.".try_into().unwrap(),
826                         signature: base64::decode("ZFGChM7QfJt0QSqVWerWnG5pMjpL1pXyJAmuHe8dHI/olmaNCxm+mqNHv9i3AploFY6JoNtiHmeBiC6zuFj/ZQ==").unwrap(),
827                 };
828                 verify_dnskey_rrsig(&dnskey_rrsig, &com_ds, dnskeys.iter().collect()).unwrap();
829                 let rrs = vec![com_ds.pop().unwrap().into(), ds_rrsig.into(),
830                         dnskeys[0].clone().into(), dnskeys[1].clone().into(), dnskey_rrsig.into()];
831                 (dnskeys, rrs)
832         }
833
834         fn mattcorallo_dnskey() -> (Vec<DnsKey>, Vec<RR>) {
835                 let com_dnskeys = com_dnskey().0;
836                 let mut mattcorallo_ds = vec![DS {
837                         name: "mattcorallo.com.".try_into().unwrap(), key_tag: 25630, alg: 13, digest_type: 2,
838                         digest: Vec::from_hex("DC608CA62BE89B3B9DB1593F9A59930D24FBA79D486E19C88A7792711EC00735").unwrap(),
839                 }];
840                 let ds_rrsig = RRSig {
841                         name: "mattcorallo.com.".try_into().unwrap(), ty: DS::TYPE, alg: 13, labels: 2, orig_ttl: 86400,
842                         expiration: 1707631252, inception: 1707022252, key_tag: 4534, key_name: "com.".try_into().unwrap(),
843                         signature: base64::decode("M7Fk+CjfLz6hRsY5iSuw5bwc2OqlS3XtKH8FDs7lcbhEiR63n+DzOF0I8L+3k06SXFnE89uuofQECzWmAyef6Q==").unwrap(),
844                 };
845                 verify_rrsig(&ds_rrsig, &com_dnskeys, mattcorallo_ds.iter().collect()).unwrap();
846                 let dnskeys = vec![DnsKey {
847                         name: "mattcorallo.com.".try_into().unwrap(), flags: 257, protocol: 3, alg: 13,
848                         pubkey: base64::decode("8BP51Etiu4V6cHvGCYqwNqCip4pvHChjEgkgG4zpdDvO9YRcTGuV/p71hAUut2/qEdxqXfUOT/082BJ/Z089DA==").unwrap(),
849                 }, DnsKey {
850                         name: "mattcorallo.com.".try_into().unwrap(), flags: 256, protocol: 3, alg: 13,
851                         pubkey: base64::decode("AhUlQ8qk7413R0m4zKfTDHb/FQRlKag+ncGXxNxT+qTzSZTb9E5IGjo9VCEp6+IMqqpkd4GrXpN9AzDvlcU9Ig==").unwrap(),
852                 }];
853                 let dnskey_rrsig = RRSig {
854                         name: "mattcorallo.com.".try_into().unwrap(), ty: DnsKey::TYPE, alg: 13, labels: 2, orig_ttl: 604800,
855                         expiration: 1708278650, inception: 1707063650, key_tag: 25630, key_name: "mattcorallo.com.".try_into().unwrap(),
856                         signature: base64::decode("nyVDwG+la8d5dyWgB7m+H3BQwCvTWLQ/kAqNruMzdLmn9B3VC9u/rvM/ortEu0WPbA1FZWJbRKpF1Ohkj3ltNw==").unwrap(),
857                 };
858                 verify_dnskey_rrsig(&dnskey_rrsig, &mattcorallo_ds, dnskeys.iter().collect()).unwrap();
859                 let rrs = vec![mattcorallo_ds.pop().unwrap().into(), ds_rrsig.into(),
860                         dnskeys[0].clone().into(), dnskeys[1].clone().into(), dnskey_rrsig.into()];
861                 (dnskeys, rrs)
862         }
863
864         fn mattcorallo_txt_record() -> (Txt, RRSig) {
865                 let txt_resp = Txt {
866                         name: "matt.user._bitcoin-payment.mattcorallo.com.".try_into().unwrap(),
867                         data: "bitcoin:?b12=lno1qsgqmqvgm96frzdg8m0gc6nzeqffvzsqzrxqy32afmr3jn9ggkwg3egfwch2hy0l6jut6vfd8vpsc3h89l6u3dm4q2d6nuamav3w27xvdmv3lpgklhg7l5teypqz9l53hj7zvuaenh34xqsz2sa967yzqkylfu9xtcd5ymcmfp32h083e805y7jfd236w9afhavqqvl8uyma7x77yun4ehe9pnhu2gekjguexmxpqjcr2j822xr7q34p078gzslf9wpwz5y57alxu99s0z2ql0kfqvwhzycqq45ehh58xnfpuek80hw6spvwrvttjrrq9pphh0dpydh06qqspp5uq4gpyt6n9mwexde44qv7lstzzq60nr40ff38u27un6y53aypmx0p4qruk2tf9mjwqlhxak4znvna5y".to_owned().into_bytes(),
868                 };
869                 let txt_rrsig = RRSig {
870                         name: "matt.user._bitcoin-payment.mattcorallo.com.".try_into().unwrap(),
871                         ty: Txt::TYPE, alg: 13, labels: 5, orig_ttl: 3600, expiration: 1708123318,
872                         inception: 1706908318, key_tag: 47959, key_name: "mattcorallo.com.".try_into().unwrap(),
873                         signature: base64::decode("mgU6iwyMWO0w9nj2Gmt1+RmaIJIU3KO7DWVZiCD1bmU9e9zNefXCtnWOC2HtwjUsn/QYkWluvuSfYpBrt1IjpQ==").unwrap(),
874                 };
875                 (txt_resp, txt_rrsig)
876         }
877
878         fn matcorallo_dnskey() -> (Vec<DnsKey>, Vec<RR>) {
879                 let com_dnskeys = com_dnskey().0;
880                 let mut matcorallo_ds = vec![DS {
881                         name: "matcorallo.com.".try_into().unwrap(), key_tag: 24930, alg: 13, digest_type: 2,
882                         digest: Vec::from_hex("693E990CBB1CE1095E387092D3C04BCE907C008891F32A88D41D3ECB129E5E23").unwrap(),
883                 }];
884                 let ds_rrsig = RRSig {
885                         name: "matcorallo.com.".try_into().unwrap(), ty: DS::TYPE, alg: 13, labels: 2, orig_ttl: 86400,
886                         expiration: 1707628636, inception: 1707019636, key_tag: 4534, key_name: "com.".try_into().unwrap(),
887                         signature: base64::decode("l9b+DhtnJSIzR6y4Bwx+0L9kep77UNCBoTg74RTSL6oMrQd8w4OobHxzwDyXqnLfyxVP18V+AnQp4DdJ2nUW1g==").unwrap(),
888                 };
889                 verify_rrsig(&ds_rrsig, &com_dnskeys, matcorallo_ds.iter().collect()).unwrap();
890                 let dnskeys = vec![DnsKey {
891                         name: "matcorallo.com.".try_into().unwrap(), flags: 257, protocol: 3, alg: 13,
892                         pubkey: base64::decode("pfO3ow3SrKhLS7AMEi3b5W9P28nCOB9vryxfSXhqMcXFP1x9V4xAt0/JLr0zNodsqRD/8d9Yhu4Wf3hnSlaavw==").unwrap(),
893                 }, DnsKey {
894                         name: "matcorallo.com.".try_into().unwrap(), flags: 256, protocol: 3, alg: 13,
895                         pubkey: base64::decode("OO6LQTV1mnRsFgn6YQoyeo/SDqS3eajfVv8WGQVnuSYO/bTS9St1tJiox2fgU6wRWDU3chhjz1Pj0unKUAQKig==").unwrap(),
896                 }];
897                 let dnskey_rrsig = RRSig {
898                         name: "matcorallo.com.".try_into().unwrap(), ty: DnsKey::TYPE, alg: 13, labels: 2, orig_ttl: 604800,
899                         expiration: 1708309135, inception: 1707094135, key_tag: 24930, key_name: "matcorallo.com.".try_into().unwrap(),
900                         signature: base64::decode("2MKg3bTn9zf4ThwCoKRFadqD6l1D6SuLksRieKxFC0QQnzUOCRgZSK2/IlT0DMEoM0+mGrJZo7UG79UILMGUyg==").unwrap(),
901                 };
902                 verify_dnskey_rrsig(&dnskey_rrsig, &matcorallo_ds, dnskeys.iter().collect()).unwrap();
903                 let rrs = vec![matcorallo_ds.pop().unwrap().into(), ds_rrsig.into(),
904                         dnskeys[0].clone().into(), dnskeys[1].clone().into(), dnskey_rrsig.into()];
905                 (dnskeys, rrs)
906         }
907
908         fn matcorallo_txt_record() -> (Txt, RRSig) {
909                 let txt_resp = Txt {
910                         name: "txt_test.matcorallo.com.".try_into().unwrap(),
911                         data: "dnssec_prover_test".to_owned().into_bytes(),
912                 };
913                 let txt_rrsig = RRSig {
914                         name: "txt_test.matcorallo.com.".try_into().unwrap(),
915                         ty: Txt::TYPE, alg: 13, labels: 3, orig_ttl: 30, expiration: 1708319203,
916                         inception: 1707104203, key_tag: 34530, key_name: "matcorallo.com.".try_into().unwrap(),
917                         signature: base64::decode("4vaE5Jex2VvIT39JpuMNT7Ds7O0OfzTik5f8WcRRxO0IJnGAO16syAsNUkNkNqsMYknnjHDF0lI4agszgzdpsw==").unwrap(),
918                 };
919                 (txt_resp, txt_rrsig)
920         }
921
922         fn matcorallo_cname_record() -> (CName, RRSig) {
923                 let cname_resp = CName {
924                         name: "cname_test.matcorallo.com.".try_into().unwrap(),
925                         canonical_name: "txt_test.matcorallo.com.".try_into().unwrap(),
926                 };
927                 let cname_rrsig = RRSig {
928                         name: "cname_test.matcorallo.com.".try_into().unwrap(),
929                         ty: CName::TYPE, alg: 13, labels: 3, orig_ttl: 30, expiration: 1708319203,
930                         inception: 1707104203, key_tag: 34530, key_name: "matcorallo.com.".try_into().unwrap(),
931                         signature: base64::decode("5HIrmEotbVb95umE6SX3NrPboKsthdcY8b7DdaYQZzm0Nj5m2VgcfOmEPJYS8o1xE4GvGGF4sdfSy3Uw7TibBg==").unwrap(),
932                 };
933                 (cname_resp, cname_rrsig)
934         }
935
936         #[test]
937         fn check_txt_record_a() {
938                 let dnskeys = mattcorallo_dnskey().0;
939                 let (txt, txt_rrsig) = mattcorallo_txt_record();
940                 let txt_resp = [txt];
941                 verify_rrsig(&txt_rrsig, &dnskeys, txt_resp.iter().collect()).unwrap();
942         }
943
944         #[test]
945         fn check_single_txt_proof() {
946                 let mut rr_stream = Vec::new();
947                 for rr in root_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
948                 for rr in com_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
949                 for rr in mattcorallo_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
950                 let (txt, txt_rrsig) = mattcorallo_txt_record();
951                 for rr in [RR::Txt(txt), RR::RRSig(txt_rrsig)] { write_rr(&rr, 1, &mut rr_stream); }
952
953                 let mut rrs = parse_rr_stream(&rr_stream).unwrap();
954                 rrs.shuffle(&mut rand::rngs::OsRng);
955                 let verified_rrs = verify_rr_stream(&rrs).unwrap();
956                 assert_eq!(verified_rrs.len(), 1);
957                 if let RR::Txt(txt) = &verified_rrs[0] {
958                         assert_eq!(txt.name.0, "matt.user._bitcoin-payment.mattcorallo.com.");
959                         assert_eq!(txt.data, b"bitcoin:?b12=lno1qsgqmqvgm96frzdg8m0gc6nzeqffvzsqzrxqy32afmr3jn9ggkwg3egfwch2hy0l6jut6vfd8vpsc3h89l6u3dm4q2d6nuamav3w27xvdmv3lpgklhg7l5teypqz9l53hj7zvuaenh34xqsz2sa967yzqkylfu9xtcd5ymcmfp32h083e805y7jfd236w9afhavqqvl8uyma7x77yun4ehe9pnhu2gekjguexmxpqjcr2j822xr7q34p078gzslf9wpwz5y57alxu99s0z2ql0kfqvwhzycqq45ehh58xnfpuek80hw6spvwrvttjrrq9pphh0dpydh06qqspp5uq4gpyt6n9mwexde44qv7lstzzq60nr40ff38u27un6y53aypmx0p4qruk2tf9mjwqlhxak4znvna5y");
960                 } else { panic!(); }
961         }
962
963         #[test]
964         fn check_txt_record_b() {
965                 let dnskeys = matcorallo_dnskey().0;
966                 let (txt, txt_rrsig) = matcorallo_txt_record();
967                 let txt_resp = [txt];
968                 verify_rrsig(&txt_rrsig, &dnskeys, txt_resp.iter().collect()).unwrap();
969         }
970
971         #[test]
972         fn check_cname_record() {
973                 let dnskeys = matcorallo_dnskey().0;
974                 let (cname, cname_rrsig) = matcorallo_cname_record();
975                 let cname_resp = [cname];
976                 verify_rrsig(&cname_rrsig, &dnskeys, cname_resp.iter().collect()).unwrap();
977         }
978
979         #[test]
980         fn check_multi_zone_proof() {
981                 let mut rr_stream = Vec::new();
982                 for rr in root_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
983                 for rr in com_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
984                 for rr in mattcorallo_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
985                 let (txt, txt_rrsig) = mattcorallo_txt_record();
986                 for rr in [RR::Txt(txt), RR::RRSig(txt_rrsig)] { write_rr(&rr, 1, &mut rr_stream); }
987                 for rr in matcorallo_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
988                 let (txt, txt_rrsig) = matcorallo_txt_record();
989                 for rr in [RR::Txt(txt), RR::RRSig(txt_rrsig)] { write_rr(&rr, 1, &mut rr_stream); }
990                 let (cname, cname_rrsig) = matcorallo_cname_record();
991                 for rr in [RR::CName(cname), RR::RRSig(cname_rrsig)] { write_rr(&rr, 1, &mut rr_stream); }
992
993                 let mut rrs = parse_rr_stream(&rr_stream).unwrap();
994                 rrs.shuffle(&mut rand::rngs::OsRng);
995                 let mut verified_rrs = verify_rr_stream(&rrs).unwrap();
996                 verified_rrs.sort();
997                 assert_eq!(verified_rrs.len(), 3);
998                 if let RR::Txt(txt) = &verified_rrs[0] {
999                         assert_eq!(txt.name.0, "matt.user._bitcoin-payment.mattcorallo.com.");
1000                         assert_eq!(txt.data, b"bitcoin:?b12=lno1qsgqmqvgm96frzdg8m0gc6nzeqffvzsqzrxqy32afmr3jn9ggkwg3egfwch2hy0l6jut6vfd8vpsc3h89l6u3dm4q2d6nuamav3w27xvdmv3lpgklhg7l5teypqz9l53hj7zvuaenh34xqsz2sa967yzqkylfu9xtcd5ymcmfp32h083e805y7jfd236w9afhavqqvl8uyma7x77yun4ehe9pnhu2gekjguexmxpqjcr2j822xr7q34p078gzslf9wpwz5y57alxu99s0z2ql0kfqvwhzycqq45ehh58xnfpuek80hw6spvwrvttjrrq9pphh0dpydh06qqspp5uq4gpyt6n9mwexde44qv7lstzzq60nr40ff38u27un6y53aypmx0p4qruk2tf9mjwqlhxak4znvna5y");
1001                 } else { panic!(); }
1002                 if let RR::Txt(txt) = &verified_rrs[1] {
1003                         assert_eq!(txt.name.0, "txt_test.matcorallo.com.");
1004                         assert_eq!(txt.data, b"dnssec_prover_test");
1005                 } else { panic!(); }
1006                 if let RR::CName(cname) = &verified_rrs[2] {
1007                         assert_eq!(cname.name.0, "cname_test.matcorallo.com.");
1008                         assert_eq!(cname.canonical_name.0, "txt_test.matcorallo.com.");
1009                 } else { panic!(); }
1010
1011         }
1012
1013         #[test]
1014         fn rfc9102_parse_test() {
1015                 // Note that this is the `AuthenticationChain` field only, and ignores the
1016                 // `ExtSupportLifetime` field (stripping the top two 0 bytes from the front).
1017 let rfc9102_test_vector = Vec::from_hex("045f343433045f74637003777777076578616d706c6503636f6d000034000100000e1000230301018bd1da95272f7fa4ffb24137fc0ed03aae67e5c4d8b3c50734e1050a7920b922045f343433045f74637003777777076578616d706c6503636f6d00002e000100000e10005f00340d0500000e105fc6d9005bfdda80074e076578616d706c6503636f6d00ce1d3adeb7dc7cee656d61cfb472c5977c8c9caeae9b765155c518fb107b6a1fe0355fbaaf753c192832fa621fa73a8b85ed79d374117387598fcc812e1ef3fb076578616d706c6503636f6d000030000100000e1000440101030d2670355e0c894d9cfea6c5af6eb7d458b57a50ba88272512d8241d8541fd54adf96ec956789a51ceb971094b3bb3f4ec49f64c686595be5b2e89e8799c7717cc076578616d706c6503636f6d00002e000100000e10005f00300d0200000e105fc6d9005bfdda80074e076578616d706c6503636f6d004628383075b8e34b743a209b27ae148d110d4e1a246138a91083249cb4a12a2d9bc4c2d7ab5eb3afb9f5d1037e4d5da8339c162a9298e9be180741a8ca74accc076578616d706c6503636f6d00002b00010002a3000024074e0d02e9b533a049798e900b5c29c90cd25a986e8a44f319ac3cd302bafc08f5b81e16076578616d706c6503636f6d00002e00010002a3000057002b0d020002a3005fc6d9005bfdda80861703636f6d00a203e704a6facbeb13fc9384fdd6de6b50de5659271f38ce81498684e6363172d47e2319fdb4a22a58a231edc2f1ff4fb2811a1807be72cb5241aa26fdaee03903636f6d00003000010002a30000440100030dec8204e43a25f2348c52a1d3bce3a265aa5d11b43dc2a471162ff341c49db9f50a2e1a41caf2e9cd20104ea0968f7511219f0bdc56b68012cc3995336751900b03636f6d00003000010002a30000440101030d45b91c3bef7a5d99a7a7c8d822e33896bc80a777a04234a605a4a8880ec7efa4e6d112c73cd3d4c65564fa74347c873723cc5f643370f166b43dedff836400ff03636f6d00003000010002a30000440101030db3373b6e22e8e49e0e1e591a9f5bd9ac5e1a0f86187fe34703f180a9d36c958f71c4af48ce0ebc5c792a724e11b43895937ee53404268129476eb1aed323939003636f6d00002e00010002a300005700300d010002a3005fc6d9005bfdda8049f303636f6d0018a948eb23d44f80abc99238fcb43c5a18debe57004f7343593f6deb6ed71e04654a433f7aa1972130d9bd921c73dcf63fcf665f2f05a0aaebafb059dc12c96503636f6d00002e00010002a300005700300d010002a3005fc6d9005bfdda80708903636f6d006170e6959bd9ed6e575837b6f580bd99dbd24a44682b0a359626a246b1812f5f9096b75e157e77848f068ae0085e1a609fc19298c33b736863fbccd4d81f5eb203636f6d00002b000100015180002449f30d0220f7a9db42d0e2042fbbb9f9ea015941202f9eabb94487e658c188e7bcb5211503636f6d00002b000100015180002470890d02ad66b3276f796223aa45eda773e92c6d98e70643bbde681db342a9e5cf2bb38003636f6d00002e0001000151800053002b0d01000151805fc6d9005bfdda807cae00122e276d45d9e9816f7922ad6ea2e73e82d26fce0a4b718625f314531ac92f8ae82418df9b898f989d32e80bc4deaba7c4a7c8f172adb57ced7fb5e77a784b0700003000010001518000440100030dccacfe0c25a4340fefba17a254f706aac1f8d14f38299025acc448ca8ce3f561f37fc3ec169fe847c8fcbe68e358ff7c71bb5ee1df0dbe518bc736d4ce8dfe1400003000010001518000440100030df303196789731ddc8a6787eff24cacfeddd032582f11a75bb1bcaa5ab321c1d7525c2658191aec01b3e98ab7915b16d571dd55b4eae51417110cc4cdd11d171100003000010001518000440101030dcaf5fe54d4d48f16621afb6bd3ad2155bacf57d1faad5bac42d17d948c421736d9389c4c4011666ea95cf17725bd0fa00ce5e714e4ec82cfdfacc9b1c863ad4600002e000100015180005300300d00000151805fc6d9005bfdda80b79d00de7a6740eeecba4bda1e5c2dd4899b2c965893f3786ce747f41e50d9de8c0a72df82560dfb48d714de3283ae99a49c0fcb50d3aaadb1a3fc62ee3a8a0988b6be").unwrap();
1018
1019                 let mut rrs = parse_rr_stream(&rfc9102_test_vector).unwrap();
1020                 rrs.shuffle(&mut rand::rngs::OsRng);
1021                 let verified_rrs = verify_rr_stream(&rrs).unwrap();
1022                 assert_eq!(verified_rrs.len(), 1);
1023                 if let RR::TLSA(tlsa) = &verified_rrs[0] {
1024                         assert_eq!(tlsa.cert_usage, 3);
1025                         assert_eq!(tlsa.selector, 1);
1026                         assert_eq!(tlsa.data_ty, 1);
1027                         assert_eq!(tlsa.data, Vec::from_hex("8bd1da95272f7fa4ffb24137fc0ed03aae67e5c4d8b3c50734e1050a7920b922").unwrap());
1028                 } else { panic!(); }
1029         }
1030 }