1 //! Resource Records are the fundamental type in the DNS - individual records mapping a name to
4 //! This module holds structs and utilities for the Resource Records supported by this crate.
7 use alloc::string::String;
8 use alloc::borrow::ToOwned;
11 use core::cmp::{self, Ordering};
16 /// A valid domain name.
18 /// It must end with a ".", be no longer than 255 bytes, consist of only printable ASCII
19 /// characters and each label may be no longer than 63 bytes.
20 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
21 pub struct Name(String);
23 /// Gets the underlying human-readable domain name
24 pub fn as_str(&self) -> &str { &self.0 }
26 impl core::ops::Deref for Name {
28 fn deref(&self) -> &str { &self.0 }
30 impl TryFrom<String> for Name {
32 fn try_from(s: String) -> Result<Name, ()> {
33 if s.is_empty() { return Err(()); }
34 if *s.as_bytes().last().unwrap_or(&0) != b"."[0] { return Err(()); }
35 if s.len() > 255 { return Err(()); }
36 if s.chars().any(|c| !c.is_ascii_graphic() || c == '"') { return Err(()); }
37 for label in s.split(".") {
38 if label.len() > 63 { return Err(()); }
44 impl TryFrom<&str> for Name {
46 fn try_from(s: &str) -> Result<Name, ()> {
47 Self::try_from(s.to_owned())
51 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
52 /// A supported Resource Record
54 /// Note that we only currently support a handful of RR types as needed to generate and validate
55 /// TXT or TLSA record proofs.
57 /// An IPv4 resource record
59 /// An IPv6 resource record
61 /// A name server resource record
63 /// A text resource record
65 /// A TLS Certificate Association resource record
67 /// A Canonical Name record
69 /// A DNS (Public) Key resource record
71 /// A Delegated Signer resource record
73 /// A Resource Record Signature record
77 /// Gets the name this record refers to.
78 pub fn name(&self) -> &Name {
80 RR::A(rr) => &rr.name,
81 RR::AAAA(rr) => &rr.name,
82 RR::NS(rr) => &rr.name,
83 RR::Txt(rr) => &rr.name,
84 RR::CName(rr) => &rr.name,
85 RR::TLSA(rr) => &rr.name,
86 RR::DnsKey(rr) => &rr.name,
87 RR::DS(rr) => &rr.name,
88 RR::RRSig(rr) => &rr.name,
91 /// Gets a JSON encoding of this record
92 pub fn json(&self) -> String {
94 RR::A(rr) => StaticRecord::json(rr),
95 RR::AAAA(rr) => StaticRecord::json(rr),
96 RR::NS(rr) => StaticRecord::json(rr),
97 RR::Txt(rr) => StaticRecord::json(rr),
98 RR::CName(rr) => StaticRecord::json(rr),
99 RR::TLSA(rr) => StaticRecord::json(rr),
100 RR::DnsKey(rr) => StaticRecord::json(rr),
101 RR::DS(rr) => StaticRecord::json(rr),
102 RR::RRSig(rr) => StaticRecord::json(rr),
105 fn ty(&self) -> u16 {
108 RR::AAAA(_) => AAAA::TYPE,
109 RR::NS(_) => NS::TYPE,
110 RR::Txt(_) => Txt::TYPE,
111 RR::CName(_) => CName::TYPE,
112 RR::TLSA(_) => TLSA::TYPE,
113 RR::DnsKey(_) => DnsKey::TYPE,
114 RR::DS(_) => DS::TYPE,
115 RR::RRSig(_) => RRSig::TYPE,
118 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
120 RR::A(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
121 RR::AAAA(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
122 RR::NS(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
123 RR::Txt(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
124 RR::CName(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
125 RR::TLSA(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
126 RR::DnsKey(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
127 RR::DS(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
128 RR::RRSig(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
132 impl From<A> for RR { fn from(a: A) -> RR { RR::A(a) } }
133 impl From<AAAA> for RR { fn from(aaaa: AAAA) -> RR { RR::AAAA(aaaa) } }
134 impl From<NS> for RR { fn from(ns: NS) -> RR { RR::NS(ns) } }
135 impl From<Txt> for RR { fn from(txt: Txt) -> RR { RR::Txt(txt) } }
136 impl From<CName> for RR { fn from(cname: CName) -> RR { RR::CName(cname) } }
137 impl From<TLSA> for RR { fn from(tlsa: TLSA) -> RR { RR::TLSA(tlsa) } }
138 impl From<DnsKey> for RR { fn from(dnskey: DnsKey) -> RR { RR::DnsKey(dnskey) } }
139 impl From<DS> for RR { fn from(ds: DS) -> RR { RR::DS(ds) } }
140 impl From<RRSig> for RR { fn from(rrsig: RRSig) -> RR { RR::RRSig(rrsig) } }
142 pub(crate) trait StaticRecord : Ord + Sized {
143 // http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4
145 fn name(&self) -> &Name;
146 fn json(&self) -> String;
147 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>);
148 fn read_from_data(name: Name, data: &[u8], wire_packet: &[u8]) -> Result<Self, ()>;
150 /// A trait describing a resource record (including the [`RR`] enum).
151 pub trait Record : Ord {
152 /// The resource record type, as maintained by IANA.
154 /// Current assignments can be found at
155 /// <http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4>
157 /// The name this record is at.
158 fn name(&self) -> &Name;
159 /// Gets a JSON encoding of this record.
160 fn json(&self) -> String;
161 /// Writes the data of this record, prefixed by a u16 length, to the given `Vec`.
162 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>);
164 impl<RR: StaticRecord> Record for RR {
165 fn ty(&self) -> u16 { RR::TYPE }
166 fn name(&self) -> &Name { RR::name(self) }
167 fn json(&self) -> String { RR::json(self) }
168 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
169 RR::write_u16_len_prefixed_data(self, out)
173 fn ty(&self) -> u16 { self.ty() }
174 fn name(&self) -> &Name { self.name() }
175 fn json(&self) -> String { self.json() }
176 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
177 self.write_u16_len_prefixed_data(out)
181 #[derive(Debug, Clone, PartialEq, Eq, Ord)]
182 /// A text resource record, containing arbitrary text data
184 /// The name this record is at.
186 /// The text record itself.
188 /// While this is generally UTF-8-valid, there is no specific requirement that it be, and thus
189 /// is an arbitrary series of bytes here.
192 impl PartialOrd for Txt {
193 fn partial_cmp(&self, o: &Txt) -> Option<Ordering> {
194 Some(self.name.cmp(&o.name)
196 // Compare in wire encoding form, i.e. compare in 255-byte chunks
197 for i in 1..(self.data.len() / 255) + 2 {
198 let start = (i - 1)*255;
199 let self_len = cmp::min(i * 255, self.data.len());
200 let o_len = cmp::min(i * 255, o.data.len());
201 let slice_cmp = self_len.cmp(&o_len)
202 .then_with(|| self.data[start..self_len].cmp(&o.data[start..o_len]));
203 if !slice_cmp.is_eq() { return slice_cmp; }
209 impl StaticRecord for Txt {
210 const TYPE: u16 = 16;
211 fn name(&self) -> &Name { &self.name }
212 fn json(&self) -> String {
213 if let Ok(s) = core::str::from_utf8(&self.data) {
214 if s.chars().all(|c| !c.is_control() && c != '"') {
215 return format!("{{\"type\":\"txt\",\"name\":\"{}\",\"contents\":\"{}\"}}", self.name.0, s);
218 format!("{{\"type\":\"txt\",\"name\":\"{}\",\"contents\":{:?}}}", self.name.0, &self.data[..])
220 fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
221 let mut parsed_data = Vec::with_capacity(data.len() - 1);
222 while !data.is_empty() {
223 let len = read_u8(&mut data)? as usize;
224 if data.len() < len { return Err(()); }
225 parsed_data.extend_from_slice(&data[..len]);
228 Ok(Txt { name, data: parsed_data })
230 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
231 let len = (self.data.len() + (self.data.len() + 254) / 255) as u16;
232 out.extend_from_slice(&len.to_be_bytes());
234 let mut data_write = &self.data[..];
235 out.extend_from_slice(&[data_write.len().try_into().unwrap_or(255)]);
236 while !data_write.is_empty() {
237 let split_pos = core::cmp::min(255, data_write.len());
238 out.extend_from_slice(&data_write[..split_pos]);
239 data_write = &data_write[split_pos..];
240 if !data_write.is_empty() {
241 out.extend_from_slice(&[data_write.len().try_into().unwrap_or(255)]);
247 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
248 /// A TLS Certificate Association resource record containing information about the TLS certificate
249 /// which should be expected when communicating with the host at the given name.
251 /// See <https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities#TLSA_RR> for more
254 /// The name this record is at.
256 /// The type of constraint on the TLS certificate(s) used which should be enforced by this
259 /// Whether to match on the full certificate, or only the public key.
261 /// The type of data included which is used to match the TLS certificate(s).
263 /// The certificate data or hash of the certificate data itself.
266 impl StaticRecord for TLSA {
267 const TYPE: u16 = 52;
268 fn name(&self) -> &Name { &self.name }
269 fn json(&self) -> String {
270 let mut out = String::with_capacity(128+self.data.len()*2);
272 "{{\"type\":\"tlsa\",\"name\":\"{}\",\"usage\":{},\"selector\":{},\"data_ty\":{},\"data\":\"",
273 self.name.0, self.cert_usage, self.selector, self.data_ty
274 ).expect("Write to a String shouldn't fail");
275 for c in self.data.iter() {
276 write!(&mut out, "{:02X}", c)
277 .expect("Write to a String shouldn't fail");
282 fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
284 name, cert_usage: read_u8(&mut data)?, selector: read_u8(&mut data)?,
285 data_ty: read_u8(&mut data)?, data: data.to_vec(),
288 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
289 let len = 3 + self.data.len();
290 out.extend_from_slice(&(len as u16).to_be_bytes());
291 out.extend_from_slice(&[self.cert_usage, self.selector, self.data_ty]);
292 out.extend_from_slice(&self.data);
296 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
297 /// A Canonical Name resource record, referring all queries for this name to another name.
299 /// The name this record is at.
301 /// The canonical name.
303 /// A resolver should use this name when looking up any further records for [`Self::name`].
304 pub canonical_name: Name,
306 impl StaticRecord for CName {
308 fn name(&self) -> &Name { &self.name }
309 fn json(&self) -> String {
310 format!("{{\"type\":\"cname\",\"name\":\"{}\",\"canonical_name\":\"{}\"}}",
311 self.name.0, self.canonical_name.0)
313 fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
314 Ok(CName { name, canonical_name: read_wire_packet_name(&mut data, wire_packet)? })
316 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
317 let len: u16 = name_len(&self.canonical_name);
318 out.extend_from_slice(&len.to_be_bytes());
319 write_name(out, &self.canonical_name);
323 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
324 /// A public key resource record which can be used to validate [`RRSig`]s.
326 /// The name this record is at.
328 /// Flags which constrain the usage of this public key.
330 /// The protocol this key is used for (protocol `3` is DNSSEC).
332 /// The algorithm which this public key uses to sign data.
334 /// The public key itself.
337 impl StaticRecord for DnsKey {
338 const TYPE: u16 = 48;
339 fn name(&self) -> &Name { &self.name }
340 fn json(&self) -> String {
341 let mut out = String::with_capacity(128+self.pubkey.len()*2);
343 "{{\"type\":\"dnskey\",\"name\":\"{}\",\"flags\":{},\"protocol\":{},\"alg\":{},\"pubkey\":\"",
344 self.name.0, self.flags, self.protocol, self.alg
345 ).expect("Write to a String shouldn't fail");
346 for c in self.pubkey.iter() {
347 write!(&mut out, "{:02X}", c)
348 .expect("Write to a String shouldn't fail");
353 fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
355 name, flags: read_u16(&mut data)?, protocol: read_u8(&mut data)?,
356 alg: read_u8(&mut data)?, pubkey: data.to_vec(),
359 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
360 let len = 2 + 1 + 1 + self.pubkey.len();
361 out.extend_from_slice(&(len as u16).to_be_bytes());
362 out.extend_from_slice(&self.flags.to_be_bytes());
363 out.extend_from_slice(&self.protocol.to_be_bytes());
364 out.extend_from_slice(&self.alg.to_be_bytes());
365 out.extend_from_slice(&self.pubkey);
369 /// A short (non-cryptographic) digest which can be used to refer to this [`DnsKey`].
370 pub fn key_tag(&self) -> u16 {
371 let mut res = u32::from(self.flags);
372 res += u32::from(self.protocol) << 8;
373 res += u32::from(self.alg);
374 for (idx, b) in self.pubkey.iter().enumerate() {
376 res += u32::from(*b) << 8;
378 res += u32::from(*b);
381 res += (res >> 16) & 0xffff;
382 (res & 0xffff) as u16
386 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
387 /// A Delegation Signer resource record which indicates that some alternative [`DnsKey`] can sign
388 /// for records in the zone which matches [`DS::name`].
390 /// The name this record is at.
392 /// This is also the zone that a [`DnsKey`] which matches the [`Self::digest`] can sign for.
394 /// A short tag which describes the matching [`DnsKey`].
396 /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which is referred to by this
399 /// The algorithm which the [`DnsKey`] referred to by this [`DS`] uses.
401 /// This matches the [`DnsKey::alg`] field in the referred-to [`DnsKey`].
403 /// The type of digest used to hash the referred-to [`DnsKey`].
405 /// The digest itself.
408 impl StaticRecord for DS {
409 const TYPE: u16 = 43;
410 fn name(&self) -> &Name { &self.name }
411 fn json(&self) -> String {
412 let mut out = String::with_capacity(128+self.digest.len()*2);
414 "{{\"type\":\"ds\",\"name\":\"{}\",\"key_tag\":{},\"alg\":{},\"digest_type\":{},\"digest\":\"",
415 self.name.0, self.key_tag, self.alg, self.digest_type
416 ).expect("Write to a String shouldn't fail");
417 for c in self.digest.iter() {
418 write!(&mut out, "{:02X}", c)
419 .expect("Write to a String shouldn't fail");
424 fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
426 name, key_tag: read_u16(&mut data)?, alg: read_u8(&mut data)?,
427 digest_type: read_u8(&mut data)?, digest: data.to_vec(),
430 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
431 let len = 2 + 1 + 1 + self.digest.len();
432 out.extend_from_slice(&(len as u16).to_be_bytes());
433 out.extend_from_slice(&self.key_tag.to_be_bytes());
434 out.extend_from_slice(&self.alg.to_be_bytes());
435 out.extend_from_slice(&self.digest_type.to_be_bytes());
436 out.extend_from_slice(&self.digest);
440 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
441 /// A Resource Record (set) Signature resource record. This contains a signature over all the
442 /// resources records of the given type at the given name.
444 /// The name this record is at.
446 /// This is also the name of any records which this signature is covering (ignoring wildcards).
448 /// The resource record type which this [`RRSig`] is signing.
450 /// All resources records of this type at the same name as [`Self::name`] must be signed by
453 /// The algorithm which is being used to sign.
455 /// This must match the [`DnsKey::alg`] field in the [`DnsKey`] being used to sign.
457 /// The number of labels in the name of the records that this signature is signing.
459 /// If this is less than the number of labels in [`Self::name`], this signature is covering a
462 /// The TTL of the records which this [`RRSig`] is signing.
464 /// The expiration (as a UNIX timestamp) of this signature.
466 /// The time (as a UNIX timestamp) at which this signature becomes valid.
468 /// A short tag which describes the matching [`DnsKey`].
470 /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which created this signature.
472 /// The [`DnsKey::name`] in the [`DnsKey`] which created this signature.
474 /// This must be a parent of the [`Self::name`].
476 /// The signature itself.
477 pub signature: Vec<u8>,
479 impl StaticRecord for RRSig {
480 const TYPE: u16 = 46;
481 fn name(&self) -> &Name { &self.name }
482 fn json(&self) -> String {
483 let mut out = String::with_capacity(256 + self.signature.len()*2);
485 "{{\"type\":\"ds\",\"name\":\"{}\",\"signed_record_type\":{},\"alg\":{},\"signed_labels\":{},\"orig_ttl\":{},\"expiration\"{},\"inception\":{},\"key_tag\":{},\"key_name\":\"{}\",\"signature\":\"",
486 self.name.0, self.ty, self.alg, self.labels, self.orig_ttl, self.expiration, self.inception, self.key_tag, self.key_name.0
487 ).expect("Write to a String shouldn't fail");
488 for c in self.signature.iter() {
489 write!(&mut out, "{:02X}", c)
490 .expect("Write to a String shouldn't fail");
495 fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
497 name, ty: read_u16(&mut data)?, alg: read_u8(&mut data)?,
498 labels: read_u8(&mut data)?, orig_ttl: read_u32(&mut data)?,
499 expiration: read_u32(&mut data)?, inception: read_u32(&mut data)?,
500 key_tag: read_u16(&mut data)?,
501 key_name: read_wire_packet_name(&mut data, wire_packet)?,
502 signature: data.to_vec(),
505 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
506 let len = 2 + 1 + 1 + 4*3 + 2 + name_len(&self.key_name) + self.signature.len() as u16;
507 out.extend_from_slice(&len.to_be_bytes());
508 out.extend_from_slice(&self.ty.to_be_bytes());
509 out.extend_from_slice(&self.alg.to_be_bytes());
510 out.extend_from_slice(&self.labels.to_be_bytes());
511 out.extend_from_slice(&self.orig_ttl.to_be_bytes());
512 out.extend_from_slice(&self.expiration.to_be_bytes());
513 out.extend_from_slice(&self.inception.to_be_bytes());
514 out.extend_from_slice(&self.key_tag.to_be_bytes());
515 write_name(out, &self.key_name);
516 out.extend_from_slice(&self.signature);
520 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
521 /// An IPv4 Address resource record
523 /// The name this record is at.
525 /// The bytes of the IPv4 address.
526 pub address: [u8; 4],
528 impl StaticRecord for A {
530 fn name(&self) -> &Name { &self.name }
531 fn json(&self) -> String {
532 format!("{{\"type\":\"a\",\"name\":\"{}\",\"address\":{:?}}}", self.name.0, self.address)
534 fn read_from_data(name: Name, data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
535 if data.len() != 4 { return Err(()); }
536 let mut address = [0; 4];
537 address.copy_from_slice(&data);
538 Ok(A { name, address })
540 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
541 out.extend_from_slice(&4u16.to_be_bytes());
542 out.extend_from_slice(&self.address);
546 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
547 /// An IPv6 Address resource record
549 /// The name this record is at.
551 /// The bytes of the IPv6 address.
552 pub address: [u8; 16],
554 impl StaticRecord for AAAA {
555 const TYPE: u16 = 28;
556 fn name(&self) -> &Name { &self.name }
557 fn json(&self) -> String {
558 format!("{{\"type\":\"aaaa\",\"name\":\"{}\",\"address\":{:?}}}", self.name.0, self.address)
560 fn read_from_data(name: Name, data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
561 if data.len() != 16 { return Err(()); }
562 let mut address = [0; 16];
563 address.copy_from_slice(&data);
564 Ok(AAAA { name, address })
566 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
567 out.extend_from_slice(&16u16.to_be_bytes());
568 out.extend_from_slice(&self.address);
572 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
573 /// A Name Server resource record, which indicates the server responsible for handling queries for
576 /// The name this record is at.
578 /// This is also the zone which the server at [`Self::name_server`] is responsible for handling
581 /// The name of the server which is responsible for handling queries for the [`Self::name`]
583 pub name_server: Name,
585 impl StaticRecord for NS {
587 fn name(&self) -> &Name { &self.name }
588 fn json(&self) -> String {
589 format!("{{\"type\":\"ns\",\"name\":\"{}\",\"ns\":\"{}\"}}", self.name.0, self.name_server.0)
591 fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
592 Ok(NS { name, name_server: read_wire_packet_name(&mut data, wire_packet)? })
594 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
595 out.extend_from_slice(&name_len(&self.name_server).to_be_bytes());
596 write_name(out, &self.name_server);