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