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 DNS (Public) Key resource record
94 /// A Delegated Signer resource record
96 /// A Resource Record Signature record
100 /// Gets the name this record refers to.
101 pub fn name(&self) -> &Name {
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,
110 fn ty(&self) -> u16 {
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,
119 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
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),
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) } }
135 trait StaticRecord : Ord {
136 // http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4
138 fn name(&self) -> &Name;
139 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>);
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.
145 /// Current assignments can be found at
146 /// <http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4>
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>);
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)
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)
168 fn read_u8(inp: &mut &[u8]) -> Result<u8, ()> {
169 let res = *inp.get(0).ok_or(())?;
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]);
178 Ok(u16::from_be_bytes(bytes))
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]);
185 Ok(u32::from_be_bytes(bytes))
188 fn read_name(inp: &mut &[u8]) -> Result<Name, ()> {
189 let mut name = String::with_capacity(1024);
191 let len = read_u8(inp)? as usize;
193 if name.is_empty() { name += "."; }
196 if inp.len() <= len { return Err(()); }
197 name += core::str::from_utf8(&inp[..len]).map_err(|_| ())?;
200 if name.len() > 1024 { return Err(()); }
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 == "." {
213 for label in canonical_name.split(".") {
214 out.write(&(label.len() as u8).to_be_bytes());
215 out.write(label.as_bytes());
219 fn name_len(name: &Name) -> u16 {
224 for label in name.split(".") {
225 res += 1 + label.len();
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..];
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]);
251 Ok(RR::Txt(Txt { name, data: parsed_data }))
254 if data_len <= 3 { return Err(()); }
256 name, cert_usage: read_u8(&mut data)?, selector: read_u8(&mut data)?,
257 data_ty: read_u8(&mut data)?, data: data.to_vec(),
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(),
268 name, key_tag: read_u16(&mut data)?, alg: read_u8(&mut data)?,
269 digest_type: read_u8(&mut data)?, digest: data.to_vec(),
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(),
284 /// Parse a stream of [`RR`]s from the format described in [RFC 9102](https://www.rfc-editor.org/rfc/rfc9102.html).
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)?);
296 /// Writes the given resource record in its wire encoding to the given `Vec`.
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);
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
311 /// The name this record is at.
313 /// The text record itself.
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.
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());
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)]);
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.
343 /// See <https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities#TLSA_RR> for more
346 /// The name this record is at.
348 /// The type of constraint on the TLS certificate(s) used which should be enforced by this
351 /// Whether to match on the full certificate, or only the public key.
353 /// The type of data included which is used to match the TLS certificate(s).
355 /// The certificate data or hash of the certificate data itself.
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);
369 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
370 /// A public key resource record which can be used to validate [`RRSig`]s.
372 /// The name this record is at.
374 /// Flags which constrain the usage of this public key.
376 /// The protocol this key is used for (protocol `3` is DNSSEC).
378 /// The algorithm which this public key uses to sign data.
380 /// The public key itself.
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);
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() {
403 res += u32::from(*b) << 8;
405 res += u32::from(*b);
408 res += (res >> 16) & 0xffff;
409 (res & 0xffff) as u16
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`].
417 /// The name this record is at.
419 /// This is also the zone that a [`DnsKey`] which matches the [`Self::digest`] can sign for.
421 /// A short tag which describes the matching [`DnsKey`].
423 /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which is referred to by this
426 /// The algorithm which the [`DnsKey`] referred to by this [`DS`] uses.
428 /// This matches the [`DnsKey::alg`] field in the referred-to [`DnsKey`].
430 /// The type of digest used to hash the referred-to [`DnsKey`].
432 /// The digest itself.
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);
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.
452 /// The name this record is at.
454 /// This is also the name of any records which this signature is covering (ignoring wildcards).
456 /// The resource record type which this [`RRSig`] is signing.
458 /// All resources records of this type at the same name as [`Self::name`] must be signed by
461 /// The algorithm which is being used to sign.
463 /// This must match the [`DnsKey::alg`] field in the [`DnsKey`] being used to sign.
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
468 /// The TTL of the records which this [`RRSig`] is signing.
470 /// The expiration (as a UNIX timestamp) of this signature.
472 /// The time (as a UNIX timestamp) at which this signature becomes valid.
474 /// A short tag which describes the matching [`DnsKey`].
476 /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which created this signature.
478 /// The [`DnsKey::name`] in the [`DnsKey`] which created this signature.
480 /// This must be a parent of the [`Self::name`].
482 /// The signature itself.
483 pub signature: Vec<u8>,
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);
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.
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.
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.
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); }
524 exponent_length = ((pubkey[1] as usize) << 8) | (pubkey[2] as usize);
527 exponent_length = pubkey[0] as usize;
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]
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); }
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; }
553 // TODO: Check orig_ttl somehow?
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);
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);
578 let alg = if sig.alg == 8 {
579 &signature::RSA_PKCS1_1024_8192_SHA256_FOR_LEGACY_USE_ONLY
581 &signature::RSA_PKCS1_1024_8192_SHA512_FOR_LEGACY_USE_ONLY
583 bytes_to_rsa_pk(&dnskey.pubkey)?
584 .verify(alg, &signed_data, &sig.signature)
585 .map_err(|_| ValidationError::Invalid)?;
588 let alg = if sig.alg == 13 {
589 &signature::ECDSA_P256_SHA256_FIXED
591 &signature::ECDSA_P384_SHA384_FIXED
594 // Add 0x4 identifier to the ECDSA pubkey as expected by ring.
595 let mut key = Vec::with_capacity(dnskey.pubkey.len() + 1);
597 key.extend_from_slice(&dnskey.pubkey);
599 signature::UnparsedPublicKey::new(alg, &key)
600 .verify(&signed_data, &sig.signature)
601 .map_err(|_| ValidationError::Invalid)?;
604 signature::UnparsedPublicKey::new(&signature::ED25519, &dnskey.pubkey)
605 .verify(&signed_data, &sig.signature)
606 .map_err(|_| ValidationError::Invalid)?;
608 _ => return Err(ValidationError::UnsupportedAlgorithm),
614 Err(ValidationError::Invalid)
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();
623 let mut had_known_digest_type = false;
624 let mut had_ds = false;
625 for ds in dses.clone() {
627 if ds.digest_type == 2 || ds.digest_type == 4 {
628 had_known_digest_type = true;
632 if !had_ds { return Err(ValidationError::Invalid); }
633 if !had_known_digest_type { return Err(ValidationError::UnsupportedAlgorithm); }
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,
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);
659 verify_rrsig(sig, validated_dnskeys.iter().map(|k| *k), records)
662 /// Verifies the given set of resource records.
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.
667 /// All records which could be validated are returned.
668 pub fn verify_rr_stream<'a>(inp: &'a [RR]) -> Result<Vec<&'a RR>, ValidationError> {
670 let mut res = Vec::new();
671 let mut next_ds_set = None;
672 'next_zone: while zone == "." || next_ds_set.is_some() {
673 let mut found_unsupported_alg = false;
674 for rrsig in inp.iter()
675 .filter_map(|rr| if let RR::RRSig(sig) = rr { Some(sig) } else { None })
676 .filter(|rrsig| rrsig.name.0 == zone && rrsig.ty == DnsKey::TYPE)
678 let dnskeys = inp.iter()
679 .filter_map(|rr| if let RR::DnsKey(dnskey) = rr { Some(dnskey) } else { None })
680 .filter(move |dnskey| dnskey.name.0 == zone);
681 let dnskeys_verified = if zone == "." {
682 verify_dnskey_rrsig(rrsig, &root_hints(), dnskeys.clone().collect())
684 debug_assert!(next_ds_set.is_some());
685 if next_ds_set.is_none() { break 'next_zone; }
686 verify_dnskey_rrsig(rrsig, next_ds_set.clone().unwrap(), dnskeys.clone().collect())
688 if dnskeys_verified.is_ok() {
689 let mut last_validated_type = None;
691 for rrsig in inp.iter()
692 .filter_map(|rr| if let RR::RRSig(sig) = rr { Some(sig) } else { None })
693 .filter(move |rrsig| rrsig.key_name.0 == zone && rrsig.name.0 != zone)
695 if !rrsig.name.ends_with(zone) { return Err(ValidationError::Invalid); }
696 if last_validated_type == Some(rrsig.ty) {
697 // If we just validated all the RRs for this type, go ahead and skip it. We
698 // may end up double-validating some RR Sets if there's multiple RRSigs for
699 // the same sets interwoven with other RRSets, but that's okay.
702 let signed_records = inp.iter()
703 .filter(|rr| rr.name() == &rrsig.name && rr.ty() == rrsig.ty);
704 verify_rrsig(rrsig, dnskeys.clone(), signed_records.clone().collect())?;
706 // RRSigs shouldn't cover child `DnsKey`s or other `RRSig`s
707 RRSig::TYPE|DnsKey::TYPE => return Err(ValidationError::Invalid),
709 next_ds_set = Some(signed_records.filter_map(|rr|
710 if let RR::DS(ds) = rr { Some(ds) }
711 else { debug_assert!(false, "We already filtered by type"); None }));
715 for record in signed_records { res.push(record); }
716 last_validated_type = Some(rrsig.ty);
720 if next_ds_set.is_none() { break 'next_zone; }
721 else { continue 'next_zone; }
722 } else if dnskeys_verified == Err(ValidationError::UnsupportedAlgorithm) {
723 // There may be redundant signatures by different keys, where one we don't supprt
724 // and another we do. Ignore ones we don't support, but if there are no more,
725 // return UnsupportedAlgorithm
726 found_unsupported_alg = true;
728 // We don't explicitly handle invalid signatures here, instead we move on to the
729 // next RRSig (if there is one) and return `Invalid` if no `RRSig`s match.
732 // No RRSigs were able to verify our DnsKey set
733 if found_unsupported_alg {
734 return Err(ValidationError::UnsupportedAlgorithm);
736 return Err(ValidationError::Invalid);
739 if res.is_empty() { Err(ValidationError::Invalid) }
747 use hex_conservative::FromHex;
749 fn root_dnskey() -> (Vec<DnsKey>, Vec<RR>) {
750 let dnskeys = vec![DnsKey {
751 name: ".".try_into().unwrap(), flags: 256, protocol: 3, alg: 8,
752 pubkey: base64::decode("AwEAAentCcIEndLh2QSK+pHFq/PkKCwioxt75d7qNOUuTPMo0Fcte/NbwDPbocvbZ/eNb5RV/xQdapaJASQ/oDLsqzD0H1+JkHNuuKc2JLtpMxg4glSE4CnRXT2CnFTW5IwOREL+zeqZHy68OXy5ngW5KALbevRYRg/q2qFezRtCSQ0knmyPwgFsghVYLKwi116oxwEU5yZ6W7npWMxt5Z+Qs8diPNWrS5aXLgJtrWUGIIuFfuZwXYziGRP/z3o1EfMo9zZU19KLopkoLXX7Ls/diCXdSEdJXTtFA8w0/OKQviuJebfKscoElCTswukVZ1VX5gbaFEo2xWhHJ9Uo63wYaTk=").unwrap(),
754 name: ".".try_into().unwrap(), flags: 257, protocol: 3, alg: 8,
755 pubkey: base64::decode("AwEAAaz/tAm8yTn4Mfeh5eyI96WSVexTBAvkMgJzkKTOiW1vkIbzxeF3+/4RgWOq7HrxRixHlFlExOLAJr5emLvN7SWXgnLh4+B5xQlNVz8Og8kvArMtNROxVQuCaSnIDdD5LKyWbRd2n9WGe2R8PzgCmr3EgVLrjyBxWezF0jLHwVN8efS3rCj/EWgvIWgb9tarpVUDK/b58Da+sqqls3eNbuv7pr+eoZG+SrDK6nWeL3c6H5Apxz7LjVc1uTIdsIXxuOLYA4/ilBmSVIzuDWfdRUfhHdY6+cn8HFRm+2hM8AnXGXws9555KrUB5qihylGa8subX2Nn6UwNR1AkUTV74bU=").unwrap(),
757 let dnskey_rrsig = RRSig {
758 name: ".".try_into().unwrap(), ty: DnsKey::TYPE, alg: 8, labels: 0, orig_ttl: 172800,
759 expiration: 1708473600, inception: 1706659200, key_tag: 20326, key_name: ".".try_into().unwrap(),
760 signature: base64::decode("ZO8LbjtwAiVkkBzOnGbiI/3ilGUPmmJpagsLSBVbIZRG6o/8a+hUZpIPTvk5ERZ1rAW4x0YxKAU8qtaHQpKIp3qYA6u97DYytVD7RdtXKHmGYAvR6QbD5eVTkCw1Sz705rJxbwt6+YM5OBweSUAy5Glo6JSQPDQwRDwj/bV2fLRhJbvfsBgxqaXJA0SaE/ceyvK8gB2NIaguTJNrztr2TENrHxi86OKOuHYDHthOW0TFoPfr19qj/P2eEC6dYniTVovUwHT7e+Hqrb05dJF4mI4ZjaIb5mFf8i5RehT1aRlnb3CLiwJ01bEjrRBo3xUn5I3PkCnglHhx3EvkO73OzA==").unwrap(),
762 let root_hints = root_hints();
763 verify_dnskey_rrsig(&dnskey_rrsig, &root_hints, dnskeys.iter().collect()).unwrap();
764 let rrs = vec![dnskeys[0].clone().into(), dnskeys[1].clone().into(), dnskey_rrsig.into()];
768 fn com_dnskey() -> (Vec<DnsKey>, Vec<RR>) {
769 let root_dnskeys = root_dnskey().0;
770 let mut com_ds = vec![DS {
771 name: "com.".try_into().unwrap(), key_tag: 19718, alg: 13, digest_type: 2,
772 digest: Vec::from_hex("8ACBB0CD28F41250A80A491389424D341522D946B0DA0C0291F2D3D771D7805A").unwrap(),
774 let ds_rrsig = RRSig {
775 name: "com.".try_into().unwrap(), ty: DS::TYPE, alg: 8, labels: 1, orig_ttl: 86400,
776 expiration: 1708189200, inception: 1707062400, key_tag: 30903, key_name: ".".try_into().unwrap(),
777 signature: base64::decode("vwMOBBwqRBdlmGZB+0FKfyMSignEtpYW9sD4TzPW2E+wdbF7O7epR5cmKmvcv0RUJdM0dGC/QmhCfgf/yqw1Xp7TpmPaYzaruW70hjGXZJO2nY3G6stUVe4S7lM2CzHL7nbbpaB5B+iSu6Ua9dZ+nyKrxfB7855HBLCLrHrkMGxWQiEPTallXXS8tEM1Y2XrsuzAQu2vZ2D2ClhFspFbPwwOdw+G6+NsZ8PnIfTkCj6DuKcgbdxjmGaYmw/6hVt9OU3kGCOBaJaEy4LrD8Kwzfu4S7axMwTKP4y4c5Y/E4k/mVAW0cuUtv549HaDfD2V0CvW1bDl6PqRkOiVsqM/lA==").unwrap(),
779 verify_rrsig(&ds_rrsig, &root_dnskeys, com_ds.iter().collect()).unwrap();
780 let dnskeys = vec![DnsKey {
781 name: "com.".try_into().unwrap(), flags: 256, protocol: 3, alg: 13,
782 pubkey: base64::decode("5i9qjJgyH+9MBz7VO269/srLQB/xRRllyUoVq8oLBZshPe4CGzDSFGnXAM3L/QPzB9ULpJuuy7jcxmBZ5Ebo7A==").unwrap(),
784 name: "com.".try_into().unwrap(), flags: 257, protocol: 3, alg: 13,
785 pubkey: base64::decode("tx8EZRAd2+K/DJRV0S+hbBzaRPS/G6JVNBitHzqpsGlz8huE61Ms9ANe6NSDLKJtiTBqfTJWDAywEp1FCsEINQ==").unwrap(),
787 let dnskey_rrsig = RRSig {
788 name: "com.".try_into().unwrap(), ty: DnsKey::TYPE, alg: 13, labels: 1, orig_ttl: 86400,
789 expiration: 1707750155, inception: 1706453855, key_tag: 19718, key_name: "com.".try_into().unwrap(),
790 signature: base64::decode("ZFGChM7QfJt0QSqVWerWnG5pMjpL1pXyJAmuHe8dHI/olmaNCxm+mqNHv9i3AploFY6JoNtiHmeBiC6zuFj/ZQ==").unwrap(),
792 verify_dnskey_rrsig(&dnskey_rrsig, &com_ds, dnskeys.iter().collect()).unwrap();
793 let rrs = vec![com_ds.pop().unwrap().into(), ds_rrsig.into(),
794 dnskeys[0].clone().into(), dnskeys[1].clone().into(), dnskey_rrsig.into()];
798 fn mattcorallo_dnskey() -> (Vec<DnsKey>, Vec<RR>) {
799 let com_dnskeys = com_dnskey().0;
800 let mut mattcorallo_ds = vec![DS {
801 name: "mattcorallo.com.".try_into().unwrap(), key_tag: 25630, alg: 13, digest_type: 2,
802 digest: Vec::from_hex("DC608CA62BE89B3B9DB1593F9A59930D24FBA79D486E19C88A7792711EC00735").unwrap(),
804 let ds_rrsig = RRSig {
805 name: "mattcorallo.com.".try_into().unwrap(), ty: DS::TYPE, alg: 13, labels: 2, orig_ttl: 86400,
806 expiration: 1707631252, inception: 1707022252, key_tag: 4534, key_name: "com.".try_into().unwrap(),
807 signature: base64::decode("M7Fk+CjfLz6hRsY5iSuw5bwc2OqlS3XtKH8FDs7lcbhEiR63n+DzOF0I8L+3k06SXFnE89uuofQECzWmAyef6Q==").unwrap(),
809 verify_rrsig(&ds_rrsig, &com_dnskeys, mattcorallo_ds.iter().collect()).unwrap();
810 let dnskeys = vec![DnsKey {
811 name: "mattcorallo.com.".try_into().unwrap(), flags: 257, protocol: 3, alg: 13,
812 pubkey: base64::decode("8BP51Etiu4V6cHvGCYqwNqCip4pvHChjEgkgG4zpdDvO9YRcTGuV/p71hAUut2/qEdxqXfUOT/082BJ/Z089DA==").unwrap(),
814 name: "mattcorallo.com.".try_into().unwrap(), flags: 256, protocol: 3, alg: 13,
815 pubkey: base64::decode("AhUlQ8qk7413R0m4zKfTDHb/FQRlKag+ncGXxNxT+qTzSZTb9E5IGjo9VCEp6+IMqqpkd4GrXpN9AzDvlcU9Ig==").unwrap(),
817 let dnskey_rrsig = RRSig {
818 name: "mattcorallo.com.".try_into().unwrap(), ty: DnsKey::TYPE, alg: 13, labels: 2, orig_ttl: 604800,
819 expiration: 1708278650, inception: 1707063650, key_tag: 25630, key_name: "mattcorallo.com.".try_into().unwrap(),
820 signature: base64::decode("nyVDwG+la8d5dyWgB7m+H3BQwCvTWLQ/kAqNruMzdLmn9B3VC9u/rvM/ortEu0WPbA1FZWJbRKpF1Ohkj3ltNw==").unwrap(),
822 verify_dnskey_rrsig(&dnskey_rrsig, &mattcorallo_ds, dnskeys.iter().collect()).unwrap();
823 let rrs = vec![mattcorallo_ds.pop().unwrap().into(), ds_rrsig.into(),
824 dnskeys[0].clone().into(), dnskeys[1].clone().into(), dnskey_rrsig.into()];
828 fn mattcorallo_txt_record() -> (Txt, RRSig) {
830 name: "matt.user._bitcoin-payment.mattcorallo.com.".try_into().unwrap(),
831 data: "bitcoin:?b12=lno1qsgqmqvgm96frzdg8m0gc6nzeqffvzsqzrxqy32afmr3jn9ggkwg3egfwch2hy0l6jut6vfd8vpsc3h89l6u3dm4q2d6nuamav3w27xvdmv3lpgklhg7l5teypqz9l53hj7zvuaenh34xqsz2sa967yzqkylfu9xtcd5ymcmfp32h083e805y7jfd236w9afhavqqvl8uyma7x77yun4ehe9pnhu2gekjguexmxpqjcr2j822xr7q34p078gzslf9wpwz5y57alxu99s0z2ql0kfqvwhzycqq45ehh58xnfpuek80hw6spvwrvttjrrq9pphh0dpydh06qqspp5uq4gpyt6n9mwexde44qv7lstzzq60nr40ff38u27un6y53aypmx0p4qruk2tf9mjwqlhxak4znvna5y".to_owned().into_bytes(),
833 let txt_rrsig = RRSig {
834 name: "matt.user._bitcoin-payment.mattcorallo.com.".try_into().unwrap(),
835 ty: Txt::TYPE, alg: 13, labels: 5, orig_ttl: 3600, expiration: 1708123318,
836 inception: 1706908318, key_tag: 47959, key_name: "mattcorallo.com.".try_into().unwrap(),
837 signature: base64::decode("mgU6iwyMWO0w9nj2Gmt1+RmaIJIU3KO7DWVZiCD1bmU9e9zNefXCtnWOC2HtwjUsn/QYkWluvuSfYpBrt1IjpQ==").unwrap(),
839 (txt_resp, txt_rrsig)
843 fn check_txt_record() {
844 let dnskeys = mattcorallo_dnskey().0;
845 let (txt, txt_rrsig) = mattcorallo_txt_record();
846 let txt_resp = [txt];
847 verify_rrsig(&txt_rrsig, &dnskeys, txt_resp.iter().collect()).unwrap();
851 fn check_txt_proof() {
852 let mut rr_stream = Vec::new();
853 for rr in root_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
854 for rr in com_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
855 for rr in mattcorallo_dnskey().1 { write_rr(&rr, 1, &mut rr_stream); }
856 let (txt, txt_rrsig) = mattcorallo_txt_record();
857 for rr in [RR::Txt(txt), RR::RRSig(txt_rrsig)] { write_rr(&rr, 1, &mut rr_stream); }
859 let rrs = parse_rr_stream(&rr_stream).unwrap();
860 let verified_rrs = verify_rr_stream(&rrs).unwrap();
861 assert_eq!(verified_rrs.len(), 1);
862 if let RR::Txt(txt) = &verified_rrs[0] {
863 assert_eq!(txt.name.0, "matt.user._bitcoin-payment.mattcorallo.com.");
864 assert_eq!(txt.data, b"bitcoin:?b12=lno1qsgqmqvgm96frzdg8m0gc6nzeqffvzsqzrxqy32afmr3jn9ggkwg3egfwch2hy0l6jut6vfd8vpsc3h89l6u3dm4q2d6nuamav3w27xvdmv3lpgklhg7l5teypqz9l53hj7zvuaenh34xqsz2sa967yzqkylfu9xtcd5ymcmfp32h083e805y7jfd236w9afhavqqvl8uyma7x77yun4ehe9pnhu2gekjguexmxpqjcr2j822xr7q34p078gzslf9wpwz5y57alxu99s0z2ql0kfqvwhzycqq45ehh58xnfpuek80hw6spvwrvttjrrq9pphh0dpydh06qqspp5uq4gpyt6n9mwexde44qv7lstzzq60nr40ff38u27un6y53aypmx0p4qruk2tf9mjwqlhxak4znvna5y");
869 fn rfc9102_parse_test() {
870 // Note that this is the `AuthenticationChain` field only, and ignores the
871 // `ExtSupportLifetime` field (stripping the top two 0 bytes from the front).
872 let rfc9102_test_vector = Vec::from_hex("045f343433045f74637003777777076578616d706c6503636f6d000034000100000e1000230301018bd1da95272f7fa4ffb24137fc0ed03aae67e5c4d8b3c50734e1050a7920b922045f343433045f74637003777777076578616d706c6503636f6d00002e000100000e10005f00340d0500000e105fc6d9005bfdda80074e076578616d706c6503636f6d00ce1d3adeb7dc7cee656d61cfb472c5977c8c9caeae9b765155c518fb107b6a1fe0355fbaaf753c192832fa621fa73a8b85ed79d374117387598fcc812e1ef3fb076578616d706c6503636f6d000030000100000e1000440101030d2670355e0c894d9cfea6c5af6eb7d458b57a50ba88272512d8241d8541fd54adf96ec956789a51ceb971094b3bb3f4ec49f64c686595be5b2e89e8799c7717cc076578616d706c6503636f6d00002e000100000e10005f00300d0200000e105fc6d9005bfdda80074e076578616d706c6503636f6d004628383075b8e34b743a209b27ae148d110d4e1a246138a91083249cb4a12a2d9bc4c2d7ab5eb3afb9f5d1037e4d5da8339c162a9298e9be180741a8ca74accc076578616d706c6503636f6d00002b00010002a3000024074e0d02e9b533a049798e900b5c29c90cd25a986e8a44f319ac3cd302bafc08f5b81e16076578616d706c6503636f6d00002e00010002a3000057002b0d020002a3005fc6d9005bfdda80861703636f6d00a203e704a6facbeb13fc9384fdd6de6b50de5659271f38ce81498684e6363172d47e2319fdb4a22a58a231edc2f1ff4fb2811a1807be72cb5241aa26fdaee03903636f6d00003000010002a30000440100030dec8204e43a25f2348c52a1d3bce3a265aa5d11b43dc2a471162ff341c49db9f50a2e1a41caf2e9cd20104ea0968f7511219f0bdc56b68012cc3995336751900b03636f6d00003000010002a30000440101030d45b91c3bef7a5d99a7a7c8d822e33896bc80a777a04234a605a4a8880ec7efa4e6d112c73cd3d4c65564fa74347c873723cc5f643370f166b43dedff836400ff03636f6d00003000010002a30000440101030db3373b6e22e8e49e0e1e591a9f5bd9ac5e1a0f86187fe34703f180a9d36c958f71c4af48ce0ebc5c792a724e11b43895937ee53404268129476eb1aed323939003636f6d00002e00010002a300005700300d010002a3005fc6d9005bfdda8049f303636f6d0018a948eb23d44f80abc99238fcb43c5a18debe57004f7343593f6deb6ed71e04654a433f7aa1972130d9bd921c73dcf63fcf665f2f05a0aaebafb059dc12c96503636f6d00002e00010002a300005700300d010002a3005fc6d9005bfdda80708903636f6d006170e6959bd9ed6e575837b6f580bd99dbd24a44682b0a359626a246b1812f5f9096b75e157e77848f068ae0085e1a609fc19298c33b736863fbccd4d81f5eb203636f6d00002b000100015180002449f30d0220f7a9db42d0e2042fbbb9f9ea015941202f9eabb94487e658c188e7bcb5211503636f6d00002b000100015180002470890d02ad66b3276f796223aa45eda773e92c6d98e70643bbde681db342a9e5cf2bb38003636f6d00002e0001000151800053002b0d01000151805fc6d9005bfdda807cae00122e276d45d9e9816f7922ad6ea2e73e82d26fce0a4b718625f314531ac92f8ae82418df9b898f989d32e80bc4deaba7c4a7c8f172adb57ced7fb5e77a784b0700003000010001518000440100030dccacfe0c25a4340fefba17a254f706aac1f8d14f38299025acc448ca8ce3f561f37fc3ec169fe847c8fcbe68e358ff7c71bb5ee1df0dbe518bc736d4ce8dfe1400003000010001518000440100030df303196789731ddc8a6787eff24cacfeddd032582f11a75bb1bcaa5ab321c1d7525c2658191aec01b3e98ab7915b16d571dd55b4eae51417110cc4cdd11d171100003000010001518000440101030dcaf5fe54d4d48f16621afb6bd3ad2155bacf57d1faad5bac42d17d948c421736d9389c4c4011666ea95cf17725bd0fa00ce5e714e4ec82cfdfacc9b1c863ad4600002e000100015180005300300d00000151805fc6d9005bfdda80b79d00de7a6740eeecba4bda1e5c2dd4899b2c965893f3786ce747f41e50d9de8c0a72df82560dfb48d714de3283ae99a49c0fcb50d3aaadb1a3fc62ee3a8a0988b6be").unwrap();
874 let rrs = parse_rr_stream(&rfc9102_test_vector).unwrap();
875 let verified_rrs = verify_rr_stream(&rrs).unwrap();
876 assert_eq!(verified_rrs.len(), 1);
877 if let RR::TLSA(tlsa) = &verified_rrs[0] {
878 assert_eq!(tlsa.cert_usage, 3);
879 assert_eq!(tlsa.selector, 1);
880 assert_eq!(tlsa.data_ty, 1);
881 assert_eq!(tlsa.data, Vec::from_hex("8bd1da95272f7fa4ffb24137fc0ed03aae67e5c4d8b3c50734e1050a7920b922").unwrap());