1 //! The DNS provides a single, global, hierarchical namespace with (when DNSSEC is used)
2 //! cryptographic guarantees on all of its data.
4 //! This makes it incredibly powerful for resolving human-readable names into arbitrary, secured
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.
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.
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.
17 #![allow(deprecated)] // XXX
18 #![deny(missing_docs)]
25 use alloc::string::String;
26 use alloc::borrow::ToOwned;
30 /// Gets the trusted root anchors
32 /// These are available at <https://data.iana.org/root-anchors/root-anchors.xml>
33 pub fn root_hints() -> Vec<DS> {
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(),
39 name: ".".try_into().unwrap(), key_tag: 20326, alg: 8, digest_type: 2,
40 digest: hex_lit::hex!("E06D44B80B8F1D39A95C0B0D7C65D08458E880409BBC683457104237C7F8EC8D").to_vec(),
42 // In tests, add the trust anchor from RFC 9102
45 name: ".".try_into().unwrap(), key_tag: 47005, alg: 13, digest_type: 2,
46 digest: hex_lit::hex!("2eb6e9f2480126691594d649a5a613de3052e37861634641bb568746f2ffc4d4").to_vec(),
51 /// A valid domain name.
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 {
59 fn deref(&self) -> &str { &self.0 }
61 impl TryFrom<String> for Name {
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(()); }
75 impl TryFrom<&str> for Name {
77 fn try_from(s: &str) -> Result<Name, ()> {
78 Self::try_from(s.to_owned())
82 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
83 /// A supported Resource Record
85 /// Note that we only currently support a handful of RR types as needed to generate and validate
86 /// TXT or TLSA record proofs.
88 /// A text resource record
90 /// A TLS Certificate Association resource record
92 /// A Canonical Name record
94 /// A DNS (Public) Key resource record
96 /// A Delegated Signer resource record
98 /// A Resource Record Signature record
102 /// Gets the name this record refers to.
103 pub fn name(&self) -> &Name {
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,
113 fn ty(&self) -> u16 {
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,
123 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
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),
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) } }
141 trait StaticRecord : Ord {
142 // http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4
144 fn name(&self) -> &Name;
145 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>);
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.
151 /// Current assignments can be found at
152 /// <http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4>
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>);
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)
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)
174 fn read_u8(inp: &mut &[u8]) -> Result<u8, ()> {
175 let res = *inp.get(0).ok_or(())?;
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]);
184 Ok(u16::from_be_bytes(bytes))
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]);
191 Ok(u32::from_be_bytes(bytes))
194 fn read_name(inp: &mut &[u8]) -> Result<Name, ()> {
195 let mut name = String::with_capacity(1024);
197 let len = read_u8(inp)? as usize;
199 if name.is_empty() { name += "."; }
202 if inp.len() <= len { return Err(()); }
203 name += core::str::from_utf8(&inp[..len]).map_err(|_| ())?;
206 if name.len() > 1024 { return Err(()); }
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 == "." {
219 for label in canonical_name.split(".") {
220 out.write(&(label.len() as u8).to_be_bytes());
221 out.write(label.as_bytes());
225 fn name_len(name: &Name) -> u16 {
230 for label in name.split(".") {
231 res += 1 + label.len();
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..];
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]);
257 Ok(RR::Txt(Txt { name, data: parsed_data }))
260 Ok(RR::CName(CName { name, canonical_name: read_name(&mut data)? }))
263 if data_len <= 3 { return Err(()); }
265 name, cert_usage: read_u8(&mut data)?, selector: read_u8(&mut data)?,
266 data_ty: read_u8(&mut data)?, data: data.to_vec(),
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(),
277 name, key_tag: read_u16(&mut data)?, alg: read_u8(&mut data)?,
278 digest_type: read_u8(&mut data)?, digest: data.to_vec(),
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(),
293 /// Parse a stream of [`RR`]s from the format described in [RFC 9102](https://www.rfc-editor.org/rfc/rfc9102.html).
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)?);
305 /// Writes the given resource record in its wire encoding to the given `Vec`.
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);
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
320 /// The name this record is at.
322 /// The text record itself.
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.
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());
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)]);
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.
352 /// See <https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities#TLSA_RR> for more
355 /// The name this record is at.
357 /// The type of constraint on the TLS certificate(s) used which should be enforced by this
360 /// Whether to match on the full certificate, or only the public key.
362 /// The type of data included which is used to match the TLS certificate(s).
364 /// The certificate data or hash of the certificate data itself.
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);
378 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
379 /// A Canonical Name resource record, referring all queries for this name to another name.
381 /// The name this record is at.
383 /// The canonical name.
385 /// A resolver should use this name when looking up any further records for [`Self::name`].
386 pub canonical_name: Name,
388 impl StaticRecord for CName {
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);
398 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
399 /// A public key resource record which can be used to validate [`RRSig`]s.
401 /// The name this record is at.
403 /// Flags which constrain the usage of this public key.
405 /// The protocol this key is used for (protocol `3` is DNSSEC).
407 /// The algorithm which this public key uses to sign data.
409 /// The public key itself.
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);
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() {
432 res += u32::from(*b) << 8;
434 res += u32::from(*b);
437 res += (res >> 16) & 0xffff;
438 (res & 0xffff) as u16
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`].
446 /// The name this record is at.
448 /// This is also the zone that a [`DnsKey`] which matches the [`Self::digest`] can sign for.
450 /// A short tag which describes the matching [`DnsKey`].
452 /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which is referred to by this
455 /// The algorithm which the [`DnsKey`] referred to by this [`DS`] uses.
457 /// This matches the [`DnsKey::alg`] field in the referred-to [`DnsKey`].
459 /// The type of digest used to hash the referred-to [`DnsKey`].
461 /// The digest itself.
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);
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.
481 /// The name this record is at.
483 /// This is also the name of any records which this signature is covering (ignoring wildcards).
485 /// The resource record type which this [`RRSig`] is signing.
487 /// All resources records of this type at the same name as [`Self::name`] must be signed by
490 /// The algorithm which is being used to sign.
492 /// This must match the [`DnsKey::alg`] field in the [`DnsKey`] being used to sign.
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
497 /// The TTL of the records which this [`RRSig`] is signing.
499 /// The expiration (as a UNIX timestamp) of this signature.
501 /// The time (as a UNIX timestamp) at which this signature becomes valid.
503 /// A short tag which describes the matching [`DnsKey`].
505 /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which created this signature.
507 /// The [`DnsKey::name`] in the [`DnsKey`] which created this signature.
509 /// This must be a parent of the [`Self::name`].
511 /// The signature itself.
512 pub signature: Vec<u8>,
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);
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.
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.
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.
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); }
553 exponent_length = ((pubkey[1] as usize) << 8) | (pubkey[2] as usize);
556 exponent_length = pubkey[0] as usize;
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]
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); }
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; }
582 // TODO: Check orig_ttl somehow?
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);
596 for record in records.iter() {
597 let periods = record.name().0.chars().filter(|c| *c == '.').count();
598 let labels = sig.labels.into();
599 if periods != 1 && periods != labels {
600 if periods < labels { return Err(ValidationError::Invalid); }
601 let signed_name = record.name().0.splitn(periods - labels + 1, ".").last();
602 debug_assert!(signed_name.is_some());
603 if let Some(name) = signed_name {
604 signed_data.extend_from_slice(b"\x01*");
605 write_name(&mut signed_data, name);
606 } else { return Err(ValidationError::Invalid); }
608 write_name(&mut signed_data, record.name());
610 signed_data.extend_from_slice(&record.ty().to_be_bytes());
611 signed_data.extend_from_slice(&1u16.to_be_bytes()); // The INternet class
612 signed_data.extend_from_slice(&sig.orig_ttl.to_be_bytes());
613 record.write_u16_len_prefixed_data(&mut signed_data);
618 let alg = if sig.alg == 8 {
619 &signature::RSA_PKCS1_1024_8192_SHA256_FOR_LEGACY_USE_ONLY
621 &signature::RSA_PKCS1_1024_8192_SHA512_FOR_LEGACY_USE_ONLY
623 bytes_to_rsa_pk(&dnskey.pubkey)?
624 .verify(alg, &signed_data, &sig.signature)
625 .map_err(|_| ValidationError::Invalid)?;
628 let alg = if sig.alg == 13 {
629 &signature::ECDSA_P256_SHA256_FIXED
631 &signature::ECDSA_P384_SHA384_FIXED
634 // Add 0x4 identifier to the ECDSA pubkey as expected by ring.
635 let mut key = Vec::with_capacity(dnskey.pubkey.len() + 1);
637 key.extend_from_slice(&dnskey.pubkey);
639 signature::UnparsedPublicKey::new(alg, &key)
640 .verify(&signed_data, &sig.signature)
641 .map_err(|_| ValidationError::Invalid)?;
644 signature::UnparsedPublicKey::new(&signature::ED25519, &dnskey.pubkey)
645 .verify(&signed_data, &sig.signature)
646 .map_err(|_| ValidationError::Invalid)?;
648 _ => return Err(ValidationError::UnsupportedAlgorithm),
654 Err(ValidationError::Invalid)
657 fn verify_dnskey_rrsig<'a, T, I>(sig: &RRSig, dses: T, records: Vec<&DnsKey>)
658 -> Result<(), ValidationError>
659 where T: IntoIterator<IntoIter = I>, I: Iterator<Item = &'a DS> + Clone {
660 let mut validated_dnskeys = Vec::with_capacity(records.len());
661 let dses = dses.into_iter();
663 let mut had_known_digest_type = false;
664 let mut had_ds = false;
665 for ds in dses.clone() {
667 if ds.digest_type == 2 || ds.digest_type == 4 {
668 had_known_digest_type = true;
672 if !had_ds { return Err(ValidationError::Invalid); }
673 if !had_known_digest_type { return Err(ValidationError::UnsupportedAlgorithm); }
675 for dnskey in records.iter() {
676 for ds in dses.clone() {
677 if ds.digest_type != 2 && ds.digest_type != 4 { continue; }
678 if ds.alg != dnskey.alg { continue; }
679 if dnskey.key_tag() == ds.key_tag {
680 let alg = match ds.digest_type {
681 2 => &ring::digest::SHA256,
682 4 => &ring::digest::SHA384,
685 let mut ctx = ring::digest::Context::new(alg);
686 write_name(&mut ctx, &dnskey.name);
687 ctx.update(&dnskey.flags.to_be_bytes());
688 ctx.update(&dnskey.protocol.to_be_bytes());
689 ctx.update(&dnskey.alg.to_be_bytes());
690 ctx.update(&dnskey.pubkey);
691 let hash = ctx.finish();
692 if hash.as_ref() == &ds.digest {
693 validated_dnskeys.push(*dnskey);
699 verify_rrsig(sig, validated_dnskeys.iter().map(|k| *k), records)
702 /// Verifies the given set of resource records.
704 /// Given a set of arbitrary records, this attempts to validate DNSSEC data from the [`root_hints`]
705 /// through to any supported non-DNSSEC record types.
707 /// All records which could be validated are returned, though if an error is found validating any
708 /// contained record, only `Err` will be returned.
709 pub fn verify_rr_stream<'a>(inp: &'a [RR]) -> Result<Vec<&'a RR>, ValidationError> {
711 let mut res = Vec::new();
712 let mut pending_ds_sets = Vec::with_capacity(1);
713 'next_zone: while zone == "." || !pending_ds_sets.is_empty() {
714 let mut found_unsupported_alg = false;
716 if let Some((next_zone, ds_set)) = pending_ds_sets.pop() {
717 next_ds_set = Some(ds_set);
720 debug_assert_eq!(zone, ".");
724 for rrsig in inp.iter()
725 .filter_map(|rr| if let RR::RRSig(sig) = rr { Some(sig) } else { None })
726 .filter(|rrsig| rrsig.name.0 == zone && rrsig.ty == DnsKey::TYPE)
728 let dnskeys = inp.iter()
729 .filter_map(|rr| if let RR::DnsKey(dnskey) = rr { Some(dnskey) } else { None })
730 .filter(move |dnskey| dnskey.name.0 == zone);
731 let dnskeys_verified = if zone == "." {
732 verify_dnskey_rrsig(rrsig, &root_hints(), dnskeys.clone().collect())
734 debug_assert!(next_ds_set.is_some());
735 if next_ds_set.is_none() { break 'next_zone; }
736 verify_dnskey_rrsig(rrsig, next_ds_set.clone().unwrap(), dnskeys.clone().collect())
738 if dnskeys_verified.is_ok() {
739 for rrsig in inp.iter()
740 .filter_map(|rr| if let RR::RRSig(sig) = rr { Some(sig) } else { None })
741 .filter(move |rrsig| rrsig.key_name.0 == zone && rrsig.name.0 != zone)
743 if !rrsig.name.ends_with(zone) { return Err(ValidationError::Invalid); }
744 let signed_records = inp.iter()
745 .filter(|rr| rr.name() == &rrsig.name && rr.ty() == rrsig.ty);
746 verify_rrsig(rrsig, dnskeys.clone(), signed_records.clone().collect())?;
748 // RRSigs shouldn't cover child `DnsKey`s or other `RRSig`s
749 RRSig::TYPE|DnsKey::TYPE => return Err(ValidationError::Invalid),
751 if !pending_ds_sets.iter().any(|(pending_zone, _)| pending_zone == &rrsig.name.0) {
752 pending_ds_sets.push((
754 signed_records.filter_map(|rr|
755 if let RR::DS(ds) = rr { Some(ds) }
756 else { debug_assert!(false, "We already filtered by type"); None })
761 for record in signed_records {
762 if !res.contains(&record) { res.push(record); }
768 } else if dnskeys_verified == Err(ValidationError::UnsupportedAlgorithm) {
769 // There may be redundant signatures by different keys, where one we don't supprt
770 // and another we do. Ignore ones we don't support, but if there are no more,
771 // return UnsupportedAlgorithm
772 found_unsupported_alg = true;
774 // We don't explicitly handle invalid signatures here, instead we move on to the
775 // next RRSig (if there is one) and return `Invalid` if no `RRSig`s match.
778 // No RRSigs were able to verify our DnsKey set
779 if found_unsupported_alg {
780 return Err(ValidationError::UnsupportedAlgorithm);
782 return Err(ValidationError::Invalid);
785 if res.is_empty() { Err(ValidationError::Invalid) }
793 use hex_conservative::FromHex;
794 use rand::seq::SliceRandom;
796 fn root_dnskey() -> (Vec<DnsKey>, Vec<RR>) {
797 let dnskeys = vec![DnsKey {
798 name: ".".try_into().unwrap(), flags: 256, protocol: 3, alg: 8,
799 pubkey: base64::decode("AwEAAentCcIEndLh2QSK+pHFq/PkKCwioxt75d7qNOUuTPMo0Fcte/NbwDPbocvbZ/eNb5RV/xQdapaJASQ/oDLsqzD0H1+JkHNuuKc2JLtpMxg4glSE4CnRXT2CnFTW5IwOREL+zeqZHy68OXy5ngW5KALbevRYRg/q2qFezRtCSQ0knmyPwgFsghVYLKwi116oxwEU5yZ6W7npWMxt5Z+Qs8diPNWrS5aXLgJtrWUGIIuFfuZwXYziGRP/z3o1EfMo9zZU19KLopkoLXX7Ls/diCXdSEdJXTtFA8w0/OKQviuJebfKscoElCTswukVZ1VX5gbaFEo2xWhHJ9Uo63wYaTk=").unwrap(),
801 name: ".".try_into().unwrap(), flags: 257, protocol: 3, alg: 8,
802 pubkey: base64::decode("AwEAAaz/tAm8yTn4Mfeh5eyI96WSVexTBAvkMgJzkKTOiW1vkIbzxeF3+/4RgWOq7HrxRixHlFlExOLAJr5emLvN7SWXgnLh4+B5xQlNVz8Og8kvArMtNROxVQuCaSnIDdD5LKyWbRd2n9WGe2R8PzgCmr3EgVLrjyBxWezF0jLHwVN8efS3rCj/EWgvIWgb9tarpVUDK/b58Da+sqqls3eNbuv7pr+eoZG+SrDK6nWeL3c6H5Apxz7LjVc1uTIdsIXxuOLYA4/ilBmSVIzuDWfdRUfhHdY6+cn8HFRm+2hM8AnXGXws9555KrUB5qihylGa8subX2Nn6UwNR1AkUTV74bU=").unwrap(),
804 let dnskey_rrsig = RRSig {
805 name: ".".try_into().unwrap(), ty: DnsKey::TYPE, alg: 8, labels: 0, orig_ttl: 172800,
806 expiration: 1708473600, inception: 1706659200, key_tag: 20326, key_name: ".".try_into().unwrap(),
807 signature: base64::decode("ZO8LbjtwAiVkkBzOnGbiI/3ilGUPmmJpagsLSBVbIZRG6o/8a+hUZpIPTvk5ERZ1rAW4x0YxKAU8qtaHQpKIp3qYA6u97DYytVD7RdtXKHmGYAvR6QbD5eVTkCw1Sz705rJxbwt6+YM5OBweSUAy5Glo6JSQPDQwRDwj/bV2fLRhJbvfsBgxqaXJA0SaE/ceyvK8gB2NIaguTJNrztr2TENrHxi86OKOuHYDHthOW0TFoPfr19qj/P2eEC6dYniTVovUwHT7e+Hqrb05dJF4mI4ZjaIb5mFf8i5RehT1aRlnb3CLiwJ01bEjrRBo3xUn5I3PkCnglHhx3EvkO73OzA==").unwrap(),
809 let root_hints = root_hints();
810 verify_dnskey_rrsig(&dnskey_rrsig, &root_hints, dnskeys.iter().collect()).unwrap();
811 let rrs = vec![dnskeys[0].clone().into(), dnskeys[1].clone().into(), dnskey_rrsig.into()];
815 fn com_dnskey() -> (Vec<DnsKey>, Vec<RR>) {
816 let root_dnskeys = root_dnskey().0;
817 let mut com_ds = vec![DS {
818 name: "com.".try_into().unwrap(), key_tag: 19718, alg: 13, digest_type: 2,
819 digest: Vec::from_hex("8ACBB0CD28F41250A80A491389424D341522D946B0DA0C0291F2D3D771D7805A").unwrap(),
821 let ds_rrsig = RRSig {
822 name: "com.".try_into().unwrap(), ty: DS::TYPE, alg: 8, labels: 1, orig_ttl: 86400,
823 expiration: 1708189200, inception: 1707062400, key_tag: 30903, key_name: ".".try_into().unwrap(),
824 signature: base64::decode("vwMOBBwqRBdlmGZB+0FKfyMSignEtpYW9sD4TzPW2E+wdbF7O7epR5cmKmvcv0RUJdM0dGC/QmhCfgf/yqw1Xp7TpmPaYzaruW70hjGXZJO2nY3G6stUVe4S7lM2CzHL7nbbpaB5B+iSu6Ua9dZ+nyKrxfB7855HBLCLrHrkMGxWQiEPTallXXS8tEM1Y2XrsuzAQu2vZ2D2ClhFspFbPwwOdw+G6+NsZ8PnIfTkCj6DuKcgbdxjmGaYmw/6hVt9OU3kGCOBaJaEy4LrD8Kwzfu4S7axMwTKP4y4c5Y/E4k/mVAW0cuUtv549HaDfD2V0CvW1bDl6PqRkOiVsqM/lA==").unwrap(),
826 verify_rrsig(&ds_rrsig, &root_dnskeys, com_ds.iter().collect()).unwrap();
827 let dnskeys = vec![DnsKey {
828 name: "com.".try_into().unwrap(), flags: 256, protocol: 3, alg: 13,
829 pubkey: base64::decode("5i9qjJgyH+9MBz7VO269/srLQB/xRRllyUoVq8oLBZshPe4CGzDSFGnXAM3L/QPzB9ULpJuuy7jcxmBZ5Ebo7A==").unwrap(),
831 name: "com.".try_into().unwrap(), flags: 257, protocol: 3, alg: 13,
832 pubkey: base64::decode("tx8EZRAd2+K/DJRV0S+hbBzaRPS/G6JVNBitHzqpsGlz8huE61Ms9ANe6NSDLKJtiTBqfTJWDAywEp1FCsEINQ==").unwrap(),
834 let dnskey_rrsig = RRSig {
835 name: "com.".try_into().unwrap(), ty: DnsKey::TYPE, alg: 13, labels: 1, orig_ttl: 86400,
836 expiration: 1707750155, inception: 1706453855, key_tag: 19718, key_name: "com.".try_into().unwrap(),
837 signature: base64::decode("ZFGChM7QfJt0QSqVWerWnG5pMjpL1pXyJAmuHe8dHI/olmaNCxm+mqNHv9i3AploFY6JoNtiHmeBiC6zuFj/ZQ==").unwrap(),
839 verify_dnskey_rrsig(&dnskey_rrsig, &com_ds, dnskeys.iter().collect()).unwrap();
840 let rrs = vec![com_ds.pop().unwrap().into(), ds_rrsig.into(),
841 dnskeys[0].clone().into(), dnskeys[1].clone().into(), dnskey_rrsig.into()];
845 fn mattcorallo_dnskey() -> (Vec<DnsKey>, Vec<RR>) {
846 let com_dnskeys = com_dnskey().0;
847 let mut mattcorallo_ds = vec![DS {
848 name: "mattcorallo.com.".try_into().unwrap(), key_tag: 25630, alg: 13, digest_type: 2,
849 digest: Vec::from_hex("DC608CA62BE89B3B9DB1593F9A59930D24FBA79D486E19C88A7792711EC00735").unwrap(),
851 let ds_rrsig = RRSig {
852 name: "mattcorallo.com.".try_into().unwrap(), ty: DS::TYPE, alg: 13, labels: 2, orig_ttl: 86400,
853 expiration: 1707631252, inception: 1707022252, key_tag: 4534, key_name: "com.".try_into().unwrap(),
854 signature: base64::decode("M7Fk+CjfLz6hRsY5iSuw5bwc2OqlS3XtKH8FDs7lcbhEiR63n+DzOF0I8L+3k06SXFnE89uuofQECzWmAyef6Q==").unwrap(),
856 verify_rrsig(&ds_rrsig, &com_dnskeys, mattcorallo_ds.iter().collect()).unwrap();
857 let dnskeys = vec![DnsKey {
858 name: "mattcorallo.com.".try_into().unwrap(), flags: 257, protocol: 3, alg: 13,
859 pubkey: base64::decode("8BP51Etiu4V6cHvGCYqwNqCip4pvHChjEgkgG4zpdDvO9YRcTGuV/p71hAUut2/qEdxqXfUOT/082BJ/Z089DA==").unwrap(),
861 name: "mattcorallo.com.".try_into().unwrap(), flags: 256, protocol: 3, alg: 13,
862 pubkey: base64::decode("AhUlQ8qk7413R0m4zKfTDHb/FQRlKag+ncGXxNxT+qTzSZTb9E5IGjo9VCEp6+IMqqpkd4GrXpN9AzDvlcU9Ig==").unwrap(),
864 let dnskey_rrsig = RRSig {
865 name: "mattcorallo.com.".try_into().unwrap(), ty: DnsKey::TYPE, alg: 13, labels: 2, orig_ttl: 604800,
866 expiration: 1708278650, inception: 1707063650, key_tag: 25630, key_name: "mattcorallo.com.".try_into().unwrap(),
867 signature: base64::decode("nyVDwG+la8d5dyWgB7m+H3BQwCvTWLQ/kAqNruMzdLmn9B3VC9u/rvM/ortEu0WPbA1FZWJbRKpF1Ohkj3ltNw==").unwrap(),
869 verify_dnskey_rrsig(&dnskey_rrsig, &mattcorallo_ds, dnskeys.iter().collect()).unwrap();
870 let rrs = vec![mattcorallo_ds.pop().unwrap().into(), ds_rrsig.into(),
871 dnskeys[0].clone().into(), dnskeys[1].clone().into(), dnskey_rrsig.into()];
875 fn mattcorallo_txt_record() -> (Txt, RRSig) {
877 name: "matt.user._bitcoin-payment.mattcorallo.com.".try_into().unwrap(),
878 data: "bitcoin:?b12=lno1qsgqmqvgm96frzdg8m0gc6nzeqffvzsqzrxqy32afmr3jn9ggkwg3egfwch2hy0l6jut6vfd8vpsc3h89l6u3dm4q2d6nuamav3w27xvdmv3lpgklhg7l5teypqz9l53hj7zvuaenh34xqsz2sa967yzqkylfu9xtcd5ymcmfp32h083e805y7jfd236w9afhavqqvl8uyma7x77yun4ehe9pnhu2gekjguexmxpqjcr2j822xr7q34p078gzslf9wpwz5y57alxu99s0z2ql0kfqvwhzycqq45ehh58xnfpuek80hw6spvwrvttjrrq9pphh0dpydh06qqspp5uq4gpyt6n9mwexde44qv7lstzzq60nr40ff38u27un6y53aypmx0p4qruk2tf9mjwqlhxak4znvna5y".to_owned().into_bytes(),
880 let txt_rrsig = RRSig {
881 name: "matt.user._bitcoin-payment.mattcorallo.com.".try_into().unwrap(),
882 ty: Txt::TYPE, alg: 13, labels: 5, orig_ttl: 3600, expiration: 1708123318,
883 inception: 1706908318, key_tag: 47959, key_name: "mattcorallo.com.".try_into().unwrap(),
884 signature: base64::decode("mgU6iwyMWO0w9nj2Gmt1+RmaIJIU3KO7DWVZiCD1bmU9e9zNefXCtnWOC2HtwjUsn/QYkWluvuSfYpBrt1IjpQ==").unwrap(),
886 (txt_resp, txt_rrsig)
889 fn matcorallo_dnskey() -> (Vec<DnsKey>, Vec<RR>) {
890 let com_dnskeys = com_dnskey().0;
891 let mut matcorallo_ds = vec![DS {
892 name: "matcorallo.com.".try_into().unwrap(), key_tag: 24930, alg: 13, digest_type: 2,
893 digest: Vec::from_hex("693E990CBB1CE1095E387092D3C04BCE907C008891F32A88D41D3ECB129E5E23").unwrap(),
895 let ds_rrsig = RRSig {
896 name: "matcorallo.com.".try_into().unwrap(), ty: DS::TYPE, alg: 13, labels: 2, orig_ttl: 86400,
897 expiration: 1707628636, inception: 1707019636, key_tag: 4534, key_name: "com.".try_into().unwrap(),
898 signature: base64::decode("l9b+DhtnJSIzR6y4Bwx+0L9kep77UNCBoTg74RTSL6oMrQd8w4OobHxzwDyXqnLfyxVP18V+AnQp4DdJ2nUW1g==").unwrap(),
900 verify_rrsig(&ds_rrsig, &com_dnskeys, matcorallo_ds.iter().collect()).unwrap();
901 let dnskeys = vec![DnsKey {
902 name: "matcorallo.com.".try_into().unwrap(), flags: 257, protocol: 3, alg: 13,
903 pubkey: base64::decode("pfO3ow3SrKhLS7AMEi3b5W9P28nCOB9vryxfSXhqMcXFP1x9V4xAt0/JLr0zNodsqRD/8d9Yhu4Wf3hnSlaavw==").unwrap(),
905 name: "matcorallo.com.".try_into().unwrap(), flags: 256, protocol: 3, alg: 13,
906 pubkey: base64::decode("OO6LQTV1mnRsFgn6YQoyeo/SDqS3eajfVv8WGQVnuSYO/bTS9St1tJiox2fgU6wRWDU3chhjz1Pj0unKUAQKig==").unwrap(),
908 let dnskey_rrsig = RRSig {
909 name: "matcorallo.com.".try_into().unwrap(), ty: DnsKey::TYPE, alg: 13, labels: 2, orig_ttl: 604800,
910 expiration: 1708309135, inception: 1707094135, key_tag: 24930, key_name: "matcorallo.com.".try_into().unwrap(),
911 signature: base64::decode("2MKg3bTn9zf4ThwCoKRFadqD6l1D6SuLksRieKxFC0QQnzUOCRgZSK2/IlT0DMEoM0+mGrJZo7UG79UILMGUyg==").unwrap(),
913 verify_dnskey_rrsig(&dnskey_rrsig, &matcorallo_ds, dnskeys.iter().collect()).unwrap();
914 let rrs = vec![matcorallo_ds.pop().unwrap().into(), ds_rrsig.into(),
915 dnskeys[0].clone().into(), dnskeys[1].clone().into(), dnskey_rrsig.into()];
919 fn matcorallo_txt_record() -> (Txt, RRSig) {
921 name: "txt_test.matcorallo.com.".try_into().unwrap(),
922 data: "dnssec_prover_test".to_owned().into_bytes(),
924 let txt_rrsig = RRSig {
925 name: "txt_test.matcorallo.com.".try_into().unwrap(),
926 ty: Txt::TYPE, alg: 13, labels: 3, orig_ttl: 30, expiration: 1708319203,
927 inception: 1707104203, key_tag: 34530, key_name: "matcorallo.com.".try_into().unwrap(),
928 signature: base64::decode("4vaE5Jex2VvIT39JpuMNT7Ds7O0OfzTik5f8WcRRxO0IJnGAO16syAsNUkNkNqsMYknnjHDF0lI4agszgzdpsw==").unwrap(),
930 (txt_resp, txt_rrsig)
933 fn matcorallo_cname_record() -> (CName, RRSig) {
934 let cname_resp = CName {
935 name: "cname_test.matcorallo.com.".try_into().unwrap(),
936 canonical_name: "txt_test.matcorallo.com.".try_into().unwrap(),
938 let cname_rrsig = RRSig {
939 name: "cname_test.matcorallo.com.".try_into().unwrap(),
940 ty: CName::TYPE, alg: 13, labels: 3, orig_ttl: 30, expiration: 1708319203,
941 inception: 1707104203, key_tag: 34530, key_name: "matcorallo.com.".try_into().unwrap(),
942 signature: base64::decode("5HIrmEotbVb95umE6SX3NrPboKsthdcY8b7DdaYQZzm0Nj5m2VgcfOmEPJYS8o1xE4GvGGF4sdfSy3Uw7TibBg==").unwrap(),
944 (cname_resp, cname_rrsig)
947 fn matcorallo_wildcard_record() -> (Txt, RRSig) {
949 name: "test.wildcard_test.matcorallo.com.".try_into().unwrap(),
950 data: "wildcard_test".to_owned().into_bytes(),
952 let txt_rrsig = RRSig {
953 name: "test.wildcard_test.matcorallo.com.".try_into().unwrap(),
954 ty: Txt::TYPE, alg: 13, labels: 3, orig_ttl: 30, expiration: 1708321778,
955 inception: 1707106778, key_tag: 34530, key_name: "matcorallo.com.".try_into().unwrap(),
956 signature: base64::decode("vdnXunPY4CnbW/BL8VOOR9o33+dqyKA/4h+u5VM7NjB30Shp8L8gL5UwE0k7TKRNgHC8j3TqEPEmNMIHz87Z4Q==").unwrap(),
958 (txt_resp, txt_rrsig)
961 fn matcorallo_cname_wildcard_record() -> (CName, RRSig, Txt, RRSig) {
962 let cname_resp = CName {
963 name: "test.cname_wildcard_test.matcorallo.com.".try_into().unwrap(),
964 canonical_name: "cname.wildcard_test.matcorallo.com.".try_into().unwrap(),
967 name: "cname.wildcard_test.matcorallo.com.".try_into().unwrap(),
968 data: "wildcard_test".to_owned().into_bytes(),
970 let cname_rrsig = RRSig {
971 name: "test.cname_wildcard_test.matcorallo.com.".try_into().unwrap(),
972 ty: CName::TYPE, alg: 13, labels: 3, orig_ttl: 30, expiration: 1708322050,
973 inception: 1707107050, key_tag: 34530, key_name: "matcorallo.com.".try_into().unwrap(),
974 signature: base64::decode("JfJuSemF5dtQYxEw6eKL4IRP8BaDt6FtbtdpZ6HjODTDflhKQRhBEbwT7kwceKPAq18q5sWHFV1bMTqE/F3WLw==").unwrap(),
976 let txt_rrsig = RRSig {
977 name: "cname.wildcard_test.matcorallo.com.".try_into().unwrap(),
978 ty: Txt::TYPE, alg: 13, labels: 3, orig_ttl: 30, expiration: 1708321778,
979 inception: 1707106778, key_tag: 34530, key_name: "matcorallo.com.".try_into().unwrap(),
980 signature: base64::decode("vdnXunPY4CnbW/BL8VOOR9o33+dqyKA/4h+u5VM7NjB30Shp8L8gL5UwE0k7TKRNgHC8j3TqEPEmNMIHz87Z4Q==").unwrap(),
982 (cname_resp, cname_rrsig, txt_resp, txt_rrsig)
986 fn check_txt_record_a() {
987 let dnskeys = mattcorallo_dnskey().0;
988 let (txt, txt_rrsig) = mattcorallo_txt_record();
989 let txt_resp = [txt];
990 verify_rrsig(&txt_rrsig, &dnskeys, txt_resp.iter().collect()).unwrap();
994 fn check_single_txt_proof() {
995 let mut rr_stream = Vec::new();
996 for rr in root_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
997 for rr in com_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
998 for rr in mattcorallo_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
999 let (txt, txt_rrsig) = mattcorallo_txt_record();
1000 for rr in [RR::Txt(txt), RR::RRSig(txt_rrsig)] { write_rr(&rr, 1, &mut rr_stream); }
1002 let mut rrs = parse_rr_stream(&rr_stream).unwrap();
1003 rrs.shuffle(&mut rand::rngs::OsRng);
1004 let verified_rrs = verify_rr_stream(&rrs).unwrap();
1005 assert_eq!(verified_rrs.len(), 1);
1006 if let RR::Txt(txt) = &verified_rrs[0] {
1007 assert_eq!(txt.name.0, "matt.user._bitcoin-payment.mattcorallo.com.");
1008 assert_eq!(txt.data, b"bitcoin:?b12=lno1qsgqmqvgm96frzdg8m0gc6nzeqffvzsqzrxqy32afmr3jn9ggkwg3egfwch2hy0l6jut6vfd8vpsc3h89l6u3dm4q2d6nuamav3w27xvdmv3lpgklhg7l5teypqz9l53hj7zvuaenh34xqsz2sa967yzqkylfu9xtcd5ymcmfp32h083e805y7jfd236w9afhavqqvl8uyma7x77yun4ehe9pnhu2gekjguexmxpqjcr2j822xr7q34p078gzslf9wpwz5y57alxu99s0z2ql0kfqvwhzycqq45ehh58xnfpuek80hw6spvwrvttjrrq9pphh0dpydh06qqspp5uq4gpyt6n9mwexde44qv7lstzzq60nr40ff38u27un6y53aypmx0p4qruk2tf9mjwqlhxak4znvna5y");
1009 } else { panic!(); }
1013 fn check_txt_record_b() {
1014 let dnskeys = matcorallo_dnskey().0;
1015 let (txt, txt_rrsig) = matcorallo_txt_record();
1016 let txt_resp = [txt];
1017 verify_rrsig(&txt_rrsig, &dnskeys, txt_resp.iter().collect()).unwrap();
1021 fn check_cname_record() {
1022 let dnskeys = matcorallo_dnskey().0;
1023 let (cname, cname_rrsig) = matcorallo_cname_record();
1024 let cname_resp = [cname];
1025 verify_rrsig(&cname_rrsig, &dnskeys, cname_resp.iter().collect()).unwrap();
1029 fn check_multi_zone_proof() {
1030 let mut rr_stream = Vec::new();
1031 for rr in root_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
1032 for rr in com_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
1033 for rr in mattcorallo_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
1034 let (txt, txt_rrsig) = mattcorallo_txt_record();
1035 for rr in [RR::Txt(txt), RR::RRSig(txt_rrsig)] { write_rr(&rr, 1, &mut rr_stream); }
1036 for rr in matcorallo_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
1037 let (txt, txt_rrsig) = matcorallo_txt_record();
1038 for rr in [RR::Txt(txt), RR::RRSig(txt_rrsig)] { write_rr(&rr, 1, &mut rr_stream); }
1039 let (cname, cname_rrsig) = matcorallo_cname_record();
1040 for rr in [RR::CName(cname), RR::RRSig(cname_rrsig)] { write_rr(&rr, 1, &mut rr_stream); }
1042 let mut rrs = parse_rr_stream(&rr_stream).unwrap();
1043 rrs.shuffle(&mut rand::rngs::OsRng);
1044 let mut verified_rrs = verify_rr_stream(&rrs).unwrap();
1045 verified_rrs.sort();
1046 assert_eq!(verified_rrs.len(), 3);
1047 if let RR::Txt(txt) = &verified_rrs[0] {
1048 assert_eq!(txt.name.0, "matt.user._bitcoin-payment.mattcorallo.com.");
1049 assert_eq!(txt.data, b"bitcoin:?b12=lno1qsgqmqvgm96frzdg8m0gc6nzeqffvzsqzrxqy32afmr3jn9ggkwg3egfwch2hy0l6jut6vfd8vpsc3h89l6u3dm4q2d6nuamav3w27xvdmv3lpgklhg7l5teypqz9l53hj7zvuaenh34xqsz2sa967yzqkylfu9xtcd5ymcmfp32h083e805y7jfd236w9afhavqqvl8uyma7x77yun4ehe9pnhu2gekjguexmxpqjcr2j822xr7q34p078gzslf9wpwz5y57alxu99s0z2ql0kfqvwhzycqq45ehh58xnfpuek80hw6spvwrvttjrrq9pphh0dpydh06qqspp5uq4gpyt6n9mwexde44qv7lstzzq60nr40ff38u27un6y53aypmx0p4qruk2tf9mjwqlhxak4znvna5y");
1050 } else { panic!(); }
1051 if let RR::Txt(txt) = &verified_rrs[1] {
1052 assert_eq!(txt.name.0, "txt_test.matcorallo.com.");
1053 assert_eq!(txt.data, b"dnssec_prover_test");
1054 } else { panic!(); }
1055 if let RR::CName(cname) = &verified_rrs[2] {
1056 assert_eq!(cname.name.0, "cname_test.matcorallo.com.");
1057 assert_eq!(cname.canonical_name.0, "txt_test.matcorallo.com.");
1058 } else { panic!(); }
1062 fn check_wildcard_record() {
1063 let dnskeys = matcorallo_dnskey().0;
1064 let (txt, txt_rrsig) = matcorallo_wildcard_record();
1065 let txt_resp = [txt];
1066 verify_rrsig(&txt_rrsig, &dnskeys, txt_resp.iter().collect()).unwrap();
1070 fn check_wildcard_proof() {
1071 let mut rr_stream = Vec::new();
1072 for rr in root_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
1073 for rr in com_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
1074 for rr in matcorallo_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
1075 let (cname, cname_rrsig, txt, txt_rrsig) = matcorallo_cname_wildcard_record();
1076 for rr in [RR::CName(cname), RR::RRSig(cname_rrsig)] { write_rr(&rr, 1, &mut rr_stream); }
1077 for rr in [RR::Txt(txt), RR::RRSig(txt_rrsig)] { write_rr(&rr, 1, &mut rr_stream); }
1079 let mut rrs = parse_rr_stream(&rr_stream).unwrap();
1080 rrs.shuffle(&mut rand::rngs::OsRng);
1081 let mut verified_rrs = verify_rr_stream(&rrs).unwrap();
1082 verified_rrs.sort();
1083 assert_eq!(verified_rrs.len(), 2);
1084 if let RR::Txt(txt) = &verified_rrs[0] {
1085 assert_eq!(txt.name.0, "cname.wildcard_test.matcorallo.com.");
1086 assert_eq!(txt.data, b"wildcard_test");
1087 } else { panic!(); }
1088 if let RR::CName(cname) = &verified_rrs[1] {
1089 assert_eq!(cname.name.0, "test.cname_wildcard_test.matcorallo.com.");
1090 assert_eq!(cname.canonical_name.0, "cname.wildcard_test.matcorallo.com.");
1091 } else { panic!(); }
1095 fn rfc9102_parse_test() {
1096 // Note that this is the `AuthenticationChain` field only, and ignores the
1097 // `ExtSupportLifetime` field (stripping the top two 0 bytes from the front).
1098 let rfc9102_test_vector = Vec::from_hex("045f343433045f74637003777777076578616d706c6503636f6d000034000100000e1000230301018bd1da95272f7fa4ffb24137fc0ed03aae67e5c4d8b3c50734e1050a7920b922045f343433045f74637003777777076578616d706c6503636f6d00002e000100000e10005f00340d0500000e105fc6d9005bfdda80074e076578616d706c6503636f6d00ce1d3adeb7dc7cee656d61cfb472c5977c8c9caeae9b765155c518fb107b6a1fe0355fbaaf753c192832fa621fa73a8b85ed79d374117387598fcc812e1ef3fb076578616d706c6503636f6d000030000100000e1000440101030d2670355e0c894d9cfea6c5af6eb7d458b57a50ba88272512d8241d8541fd54adf96ec956789a51ceb971094b3bb3f4ec49f64c686595be5b2e89e8799c7717cc076578616d706c6503636f6d00002e000100000e10005f00300d0200000e105fc6d9005bfdda80074e076578616d706c6503636f6d004628383075b8e34b743a209b27ae148d110d4e1a246138a91083249cb4a12a2d9bc4c2d7ab5eb3afb9f5d1037e4d5da8339c162a9298e9be180741a8ca74accc076578616d706c6503636f6d00002b00010002a3000024074e0d02e9b533a049798e900b5c29c90cd25a986e8a44f319ac3cd302bafc08f5b81e16076578616d706c6503636f6d00002e00010002a3000057002b0d020002a3005fc6d9005bfdda80861703636f6d00a203e704a6facbeb13fc9384fdd6de6b50de5659271f38ce81498684e6363172d47e2319fdb4a22a58a231edc2f1ff4fb2811a1807be72cb5241aa26fdaee03903636f6d00003000010002a30000440100030dec8204e43a25f2348c52a1d3bce3a265aa5d11b43dc2a471162ff341c49db9f50a2e1a41caf2e9cd20104ea0968f7511219f0bdc56b68012cc3995336751900b03636f6d00003000010002a30000440101030d45b91c3bef7a5d99a7a7c8d822e33896bc80a777a04234a605a4a8880ec7efa4e6d112c73cd3d4c65564fa74347c873723cc5f643370f166b43dedff836400ff03636f6d00003000010002a30000440101030db3373b6e22e8e49e0e1e591a9f5bd9ac5e1a0f86187fe34703f180a9d36c958f71c4af48ce0ebc5c792a724e11b43895937ee53404268129476eb1aed323939003636f6d00002e00010002a300005700300d010002a3005fc6d9005bfdda8049f303636f6d0018a948eb23d44f80abc99238fcb43c5a18debe57004f7343593f6deb6ed71e04654a433f7aa1972130d9bd921c73dcf63fcf665f2f05a0aaebafb059dc12c96503636f6d00002e00010002a300005700300d010002a3005fc6d9005bfdda80708903636f6d006170e6959bd9ed6e575837b6f580bd99dbd24a44682b0a359626a246b1812f5f9096b75e157e77848f068ae0085e1a609fc19298c33b736863fbccd4d81f5eb203636f6d00002b000100015180002449f30d0220f7a9db42d0e2042fbbb9f9ea015941202f9eabb94487e658c188e7bcb5211503636f6d00002b000100015180002470890d02ad66b3276f796223aa45eda773e92c6d98e70643bbde681db342a9e5cf2bb38003636f6d00002e0001000151800053002b0d01000151805fc6d9005bfdda807cae00122e276d45d9e9816f7922ad6ea2e73e82d26fce0a4b718625f314531ac92f8ae82418df9b898f989d32e80bc4deaba7c4a7c8f172adb57ced7fb5e77a784b0700003000010001518000440100030dccacfe0c25a4340fefba17a254f706aac1f8d14f38299025acc448ca8ce3f561f37fc3ec169fe847c8fcbe68e358ff7c71bb5ee1df0dbe518bc736d4ce8dfe1400003000010001518000440100030df303196789731ddc8a6787eff24cacfeddd032582f11a75bb1bcaa5ab321c1d7525c2658191aec01b3e98ab7915b16d571dd55b4eae51417110cc4cdd11d171100003000010001518000440101030dcaf5fe54d4d48f16621afb6bd3ad2155bacf57d1faad5bac42d17d948c421736d9389c4c4011666ea95cf17725bd0fa00ce5e714e4ec82cfdfacc9b1c863ad4600002e000100015180005300300d00000151805fc6d9005bfdda80b79d00de7a6740eeecba4bda1e5c2dd4899b2c965893f3786ce747f41e50d9de8c0a72df82560dfb48d714de3283ae99a49c0fcb50d3aaadb1a3fc62ee3a8a0988b6be").unwrap();
1100 let mut rrs = parse_rr_stream(&rfc9102_test_vector).unwrap();
1101 rrs.shuffle(&mut rand::rngs::OsRng);
1102 let verified_rrs = verify_rr_stream(&rrs).unwrap();
1103 assert_eq!(verified_rrs.len(), 1);
1104 if let RR::TLSA(tlsa) = &verified_rrs[0] {
1105 assert_eq!(tlsa.cert_usage, 3);
1106 assert_eq!(tlsa.selector, 1);
1107 assert_eq!(tlsa.data_ty, 1);
1108 assert_eq!(tlsa.data, Vec::from_hex("8bd1da95272f7fa4ffb24137fc0ed03aae67e5c4d8b3c50734e1050a7920b922").unwrap());
1109 } else { panic!(); }