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};
17 /// A valid domain name.
19 /// It must end with a ".", be no longer than 255 bytes, consist of only printable ASCII
20 /// characters and each label may be no longer than 63 bytes.
21 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
22 pub struct Name(String);
24 /// Gets the underlying human-readable domain name
25 pub fn as_str(&self) -> &str { &self.0 }
27 impl core::ops::Deref for Name {
29 fn deref(&self) -> &str { &self.0 }
31 impl fmt::Display for Name {
32 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
36 impl TryFrom<String> for Name {
38 fn try_from(s: String) -> Result<Name, ()> {
39 if s.is_empty() { return Err(()); }
40 if *s.as_bytes().last().unwrap_or(&0) != b"."[0] { return Err(()); }
41 if s.len() > 255 { return Err(()); }
42 if s.chars().any(|c| !c.is_ascii_graphic() || c == '"') { return Err(()); }
43 for label in s.split(".") {
44 if label.len() > 63 { return Err(()); }
50 impl TryFrom<&str> for Name {
52 fn try_from(s: &str) -> Result<Name, ()> {
53 Self::try_from(s.to_owned())
57 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
58 /// A supported Resource Record
60 /// Note that we only currently support a handful of RR types as needed to generate and validate
61 /// TXT or TLSA record proofs.
63 /// An IPv4 resource record
65 /// An IPv6 resource record
67 /// A name server resource record
69 /// A text resource record
71 /// A TLS Certificate Association resource record
73 /// A Canonical Name record
75 /// A DNS (Public) Key resource record
77 /// A Delegated Signer resource record
79 /// A Resource Record Signature record
83 /// Gets the name this record refers to.
84 pub fn name(&self) -> &Name {
86 RR::A(rr) => &rr.name,
87 RR::AAAA(rr) => &rr.name,
88 RR::NS(rr) => &rr.name,
89 RR::Txt(rr) => &rr.name,
90 RR::CName(rr) => &rr.name,
91 RR::TLSA(rr) => &rr.name,
92 RR::DnsKey(rr) => &rr.name,
93 RR::DS(rr) => &rr.name,
94 RR::RRSig(rr) => &rr.name,
97 /// Gets a JSON encoding of this record
98 pub fn json(&self) -> String {
100 RR::A(rr) => StaticRecord::json(rr),
101 RR::AAAA(rr) => StaticRecord::json(rr),
102 RR::NS(rr) => StaticRecord::json(rr),
103 RR::Txt(rr) => StaticRecord::json(rr),
104 RR::CName(rr) => StaticRecord::json(rr),
105 RR::TLSA(rr) => StaticRecord::json(rr),
106 RR::DnsKey(rr) => StaticRecord::json(rr),
107 RR::DS(rr) => StaticRecord::json(rr),
108 RR::RRSig(rr) => StaticRecord::json(rr),
111 fn ty(&self) -> u16 {
114 RR::AAAA(_) => AAAA::TYPE,
115 RR::NS(_) => NS::TYPE,
116 RR::Txt(_) => Txt::TYPE,
117 RR::CName(_) => CName::TYPE,
118 RR::TLSA(_) => TLSA::TYPE,
119 RR::DnsKey(_) => DnsKey::TYPE,
120 RR::DS(_) => DS::TYPE,
121 RR::RRSig(_) => RRSig::TYPE,
124 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
126 RR::A(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
127 RR::AAAA(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
128 RR::NS(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
129 RR::Txt(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
130 RR::CName(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
131 RR::TLSA(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
132 RR::DnsKey(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
133 RR::DS(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
134 RR::RRSig(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
138 impl From<A> for RR { fn from(a: A) -> RR { RR::A(a) } }
139 impl From<AAAA> for RR { fn from(aaaa: AAAA) -> RR { RR::AAAA(aaaa) } }
140 impl From<NS> for RR { fn from(ns: NS) -> RR { RR::NS(ns) } }
141 impl From<Txt> for RR { fn from(txt: Txt) -> RR { RR::Txt(txt) } }
142 impl From<CName> for RR { fn from(cname: CName) -> RR { RR::CName(cname) } }
143 impl From<TLSA> for RR { fn from(tlsa: TLSA) -> RR { RR::TLSA(tlsa) } }
144 impl From<DnsKey> for RR { fn from(dnskey: DnsKey) -> RR { RR::DnsKey(dnskey) } }
145 impl From<DS> for RR { fn from(ds: DS) -> RR { RR::DS(ds) } }
146 impl From<RRSig> for RR { fn from(rrsig: RRSig) -> RR { RR::RRSig(rrsig) } }
148 pub(crate) trait StaticRecord : Ord + Sized {
149 // http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4
151 fn name(&self) -> &Name;
152 fn json(&self) -> String;
153 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>);
154 fn read_from_data(name: Name, data: &[u8], wire_packet: &[u8]) -> Result<Self, ()>;
156 /// A trait describing a resource record (including the [`RR`] enum).
157 pub trait Record : Ord {
158 /// The resource record type, as maintained by IANA.
160 /// Current assignments can be found at
161 /// <http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4>
163 /// The name this record is at.
164 fn name(&self) -> &Name;
165 /// Gets a JSON encoding of this record.
166 fn json(&self) -> String;
167 /// Writes the data of this record, prefixed by a u16 length, to the given `Vec`.
168 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>);
170 impl<RR: StaticRecord> Record for RR {
171 fn ty(&self) -> u16 { RR::TYPE }
172 fn name(&self) -> &Name { RR::name(self) }
173 fn json(&self) -> String { RR::json(self) }
174 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
175 RR::write_u16_len_prefixed_data(self, out)
179 fn ty(&self) -> u16 { self.ty() }
180 fn name(&self) -> &Name { self.name() }
181 fn json(&self) -> String { self.json() }
182 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
183 self.write_u16_len_prefixed_data(out)
187 #[derive(Debug, Clone, PartialEq, Eq, Ord)]
188 /// A text resource record, containing arbitrary text data
190 /// The name this record is at.
192 /// The text record itself.
194 /// While this is generally UTF-8-valid, there is no specific requirement that it be, and thus
195 /// is an arbitrary series of bytes here.
198 impl PartialOrd for Txt {
199 fn partial_cmp(&self, o: &Txt) -> Option<Ordering> {
200 Some(self.name.cmp(&o.name)
202 // Compare in wire encoding form, i.e. compare in 255-byte chunks
203 for i in 1..(self.data.len() / 255) + 2 {
204 let start = (i - 1)*255;
205 let self_len = cmp::min(i * 255, self.data.len());
206 let o_len = cmp::min(i * 255, o.data.len());
207 let slice_cmp = self_len.cmp(&o_len)
208 .then_with(|| self.data[start..self_len].cmp(&o.data[start..o_len]));
209 if !slice_cmp.is_eq() { return slice_cmp; }
215 impl StaticRecord for Txt {
216 const TYPE: u16 = 16;
217 fn name(&self) -> &Name { &self.name }
218 fn json(&self) -> String {
219 if let Ok(s) = core::str::from_utf8(&self.data) {
220 if s.chars().all(|c| !c.is_control() && c != '"') {
221 return format!("{{\"type\":\"txt\",\"name\":\"{}\",\"contents\":\"{}\"}}", self.name.0, s);
224 format!("{{\"type\":\"txt\",\"name\":\"{}\",\"contents\":{:?}}}", self.name.0, &self.data[..])
226 fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
227 let mut parsed_data = Vec::with_capacity(data.len().saturating_sub(1));
228 while !data.is_empty() {
229 let len = read_u8(&mut data)? as usize;
230 if data.len() < len { return Err(()); }
231 parsed_data.extend_from_slice(&data[..len]);
234 Ok(Txt { name, data: parsed_data })
236 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
237 let len = (self.data.len() + (self.data.len() + 254) / 255) as u16;
238 out.extend_from_slice(&len.to_be_bytes());
240 let mut data_write = &self.data[..];
241 out.extend_from_slice(&[data_write.len().try_into().unwrap_or(255)]);
242 while !data_write.is_empty() {
243 let split_pos = core::cmp::min(255, data_write.len());
244 out.extend_from_slice(&data_write[..split_pos]);
245 data_write = &data_write[split_pos..];
246 if !data_write.is_empty() {
247 out.extend_from_slice(&[data_write.len().try_into().unwrap_or(255)]);
253 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
254 /// A TLS Certificate Association resource record containing information about the TLS certificate
255 /// which should be expected when communicating with the host at the given name.
257 /// See <https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities#TLSA_RR> for more
260 /// The name this record is at.
262 /// The type of constraint on the TLS certificate(s) used which should be enforced by this
265 /// Whether to match on the full certificate, or only the public key.
267 /// The type of data included which is used to match the TLS certificate(s).
269 /// The certificate data or hash of the certificate data itself.
272 impl StaticRecord for TLSA {
273 const TYPE: u16 = 52;
274 fn name(&self) -> &Name { &self.name }
275 fn json(&self) -> String {
276 let mut out = String::with_capacity(128+self.data.len()*2);
278 "{{\"type\":\"tlsa\",\"name\":\"{}\",\"usage\":{},\"selector\":{},\"data_ty\":{},\"data\":\"",
279 self.name.0, self.cert_usage, self.selector, self.data_ty
280 ).expect("Write to a String shouldn't fail");
281 for c in self.data.iter() {
282 write!(&mut out, "{:02X}", c)
283 .expect("Write to a String shouldn't fail");
288 fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
290 name, cert_usage: read_u8(&mut data)?, selector: read_u8(&mut data)?,
291 data_ty: read_u8(&mut data)?, data: data.to_vec(),
294 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
295 let len = 3 + self.data.len();
296 out.extend_from_slice(&(len as u16).to_be_bytes());
297 out.extend_from_slice(&[self.cert_usage, self.selector, self.data_ty]);
298 out.extend_from_slice(&self.data);
302 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
303 /// A Canonical Name resource record, referring all queries for this name to another name.
305 /// The name this record is at.
307 /// The canonical name.
309 /// A resolver should use this name when looking up any further records for [`self.name`].
310 pub canonical_name: Name,
312 impl StaticRecord for CName {
314 fn name(&self) -> &Name { &self.name }
315 fn json(&self) -> String {
316 format!("{{\"type\":\"cname\",\"name\":\"{}\",\"canonical_name\":\"{}\"}}",
317 self.name.0, self.canonical_name.0)
319 fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
320 Ok(CName { name, canonical_name: read_wire_packet_name(&mut data, wire_packet)? })
322 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
323 let len: u16 = name_len(&self.canonical_name);
324 out.extend_from_slice(&len.to_be_bytes());
325 write_name(out, &self.canonical_name);
329 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
330 /// A public key resource record which can be used to validate [`RRSig`]s.
332 /// The name this record is at.
334 /// Flags which constrain the usage of this public key.
336 /// The protocol this key is used for (protocol `3` is DNSSEC).
338 /// The algorithm which this public key uses to sign data.
340 /// The public key itself.
343 impl StaticRecord for DnsKey {
344 const TYPE: u16 = 48;
345 fn name(&self) -> &Name { &self.name }
346 fn json(&self) -> String {
347 let mut out = String::with_capacity(128+self.pubkey.len()*2);
349 "{{\"type\":\"dnskey\",\"name\":\"{}\",\"flags\":{},\"protocol\":{},\"alg\":{},\"pubkey\":\"",
350 self.name.0, self.flags, self.protocol, self.alg
351 ).expect("Write to a String shouldn't fail");
352 for c in self.pubkey.iter() {
353 write!(&mut out, "{:02X}", c)
354 .expect("Write to a String shouldn't fail");
359 fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
361 name, flags: read_u16(&mut data)?, protocol: read_u8(&mut data)?,
362 alg: read_u8(&mut data)?, pubkey: data.to_vec(),
365 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
366 let len = 2 + 1 + 1 + self.pubkey.len();
367 out.extend_from_slice(&(len as u16).to_be_bytes());
368 out.extend_from_slice(&self.flags.to_be_bytes());
369 out.extend_from_slice(&self.protocol.to_be_bytes());
370 out.extend_from_slice(&self.alg.to_be_bytes());
371 out.extend_from_slice(&self.pubkey);
375 /// A short (non-cryptographic) digest which can be used to refer to this [`DnsKey`].
376 pub fn key_tag(&self) -> u16 {
377 let mut res = u32::from(self.flags);
378 res += u32::from(self.protocol) << 8;
379 res += u32::from(self.alg);
380 for (idx, b) in self.pubkey.iter().enumerate() {
382 res += u32::from(*b) << 8;
384 res += u32::from(*b);
387 res += (res >> 16) & 0xffff;
388 (res & 0xffff) as u16
392 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
393 /// A Delegation Signer resource record which indicates that some alternative [`DnsKey`] can sign
394 /// for records in the zone which matches [`self.name`].
396 /// The name this record is at.
398 /// This is also the zone that a [`DnsKey`] which matches the [`Self::digest`] can sign for.
400 /// A short tag which describes the matching [`DnsKey`].
402 /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which is referred to by this
405 /// The algorithm which the [`DnsKey`] referred to by this [`DS`] uses.
407 /// This matches the [`DnsKey::alg`] field in the referred-to [`DnsKey`].
409 /// The type of digest used to hash the referred-to [`DnsKey`].
411 /// The digest itself.
414 impl StaticRecord for DS {
415 const TYPE: u16 = 43;
416 fn name(&self) -> &Name { &self.name }
417 fn json(&self) -> String {
418 let mut out = String::with_capacity(128+self.digest.len()*2);
420 "{{\"type\":\"ds\",\"name\":\"{}\",\"key_tag\":{},\"alg\":{},\"digest_type\":{},\"digest\":\"",
421 self.name.0, self.key_tag, self.alg, self.digest_type
422 ).expect("Write to a String shouldn't fail");
423 for c in self.digest.iter() {
424 write!(&mut out, "{:02X}", c)
425 .expect("Write to a String shouldn't fail");
430 fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
432 name, key_tag: read_u16(&mut data)?, alg: read_u8(&mut data)?,
433 digest_type: read_u8(&mut data)?, digest: data.to_vec(),
436 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
437 let len = 2 + 1 + 1 + self.digest.len();
438 out.extend_from_slice(&(len as u16).to_be_bytes());
439 out.extend_from_slice(&self.key_tag.to_be_bytes());
440 out.extend_from_slice(&self.alg.to_be_bytes());
441 out.extend_from_slice(&self.digest_type.to_be_bytes());
442 out.extend_from_slice(&self.digest);
446 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
447 /// A Resource Record (set) Signature resource record. This contains a signature over all the
448 /// resources records of the given type at the given name.
450 /// The name this record is at.
452 /// This is also the name of any records which this signature is covering (ignoring wildcards).
454 /// The resource record type which this [`RRSig`] is signing.
456 /// All resources records of this type at the same name as [`self.name`] must be signed by
459 /// The algorithm which is being used to sign.
461 /// This must match the [`DnsKey::alg`] field in the [`DnsKey`] being used to sign.
463 /// The number of labels in the name of the records that this signature is signing.
465 /// If this is less than the number of labels in [`self.name`], this signature is covering a
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 [`self.name`].
482 /// [`DnsKey::name`]: Record::name
483 // We'd like to just link to the `DnsKey` member variable called `name`, but there doesn't
484 // appear to be a way to actually do that, so instead we have to link to the trait method.
486 /// The signature itself.
487 pub signature: Vec<u8>,
489 impl StaticRecord for RRSig {
490 const TYPE: u16 = 46;
491 fn name(&self) -> &Name { &self.name }
492 fn json(&self) -> String {
493 let mut out = String::with_capacity(256 + self.signature.len()*2);
495 "{{\"type\":\"ds\",\"name\":\"{}\",\"signed_record_type\":{},\"alg\":{},\"signed_labels\":{},\"orig_ttl\":{},\"expiration\"{},\"inception\":{},\"key_tag\":{},\"key_name\":\"{}\",\"signature\":\"",
496 self.name.0, self.ty, self.alg, self.labels, self.orig_ttl, self.expiration, self.inception, self.key_tag, self.key_name.0
497 ).expect("Write to a String shouldn't fail");
498 for c in self.signature.iter() {
499 write!(&mut out, "{:02X}", c)
500 .expect("Write to a String shouldn't fail");
505 fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
507 name, ty: read_u16(&mut data)?, alg: read_u8(&mut data)?,
508 labels: read_u8(&mut data)?, orig_ttl: read_u32(&mut data)?,
509 expiration: read_u32(&mut data)?, inception: read_u32(&mut data)?,
510 key_tag: read_u16(&mut data)?,
511 key_name: read_wire_packet_name(&mut data, wire_packet)?,
512 signature: data.to_vec(),
515 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
516 let len = 2 + 1 + 1 + 4*3 + 2 + name_len(&self.key_name) + self.signature.len() as u16;
517 out.extend_from_slice(&len.to_be_bytes());
518 out.extend_from_slice(&self.ty.to_be_bytes());
519 out.extend_from_slice(&self.alg.to_be_bytes());
520 out.extend_from_slice(&self.labels.to_be_bytes());
521 out.extend_from_slice(&self.orig_ttl.to_be_bytes());
522 out.extend_from_slice(&self.expiration.to_be_bytes());
523 out.extend_from_slice(&self.inception.to_be_bytes());
524 out.extend_from_slice(&self.key_tag.to_be_bytes());
525 write_name(out, &self.key_name);
526 out.extend_from_slice(&self.signature);
530 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
531 /// An IPv4 Address resource record
533 /// The name this record is at.
535 /// The bytes of the IPv4 address.
536 pub address: [u8; 4],
538 impl StaticRecord for A {
540 fn name(&self) -> &Name { &self.name }
541 fn json(&self) -> String {
542 format!("{{\"type\":\"a\",\"name\":\"{}\",\"address\":{:?}}}", self.name.0, self.address)
544 fn read_from_data(name: Name, data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
545 if data.len() != 4 { return Err(()); }
546 let mut address = [0; 4];
547 address.copy_from_slice(&data);
548 Ok(A { name, address })
550 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
551 out.extend_from_slice(&4u16.to_be_bytes());
552 out.extend_from_slice(&self.address);
556 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
557 /// An IPv6 Address resource record
559 /// The name this record is at.
561 /// The bytes of the IPv6 address.
562 pub address: [u8; 16],
564 impl StaticRecord for AAAA {
565 const TYPE: u16 = 28;
566 fn name(&self) -> &Name { &self.name }
567 fn json(&self) -> String {
568 format!("{{\"type\":\"aaaa\",\"name\":\"{}\",\"address\":{:?}}}", self.name.0, self.address)
570 fn read_from_data(name: Name, data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
571 if data.len() != 16 { return Err(()); }
572 let mut address = [0; 16];
573 address.copy_from_slice(&data);
574 Ok(AAAA { name, address })
576 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
577 out.extend_from_slice(&16u16.to_be_bytes());
578 out.extend_from_slice(&self.address);
582 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
583 /// A Name Server resource record, which indicates the server responsible for handling queries for
586 /// The name this record is at.
588 /// This is also the zone which the server at [`Self::name_server`] is responsible for handling
591 /// The name of the server which is responsible for handling queries for the [`self.name`]
593 pub name_server: Name,
595 impl StaticRecord for NS {
597 fn name(&self) -> &Name { &self.name }
598 fn json(&self) -> String {
599 format!("{{\"type\":\"ns\",\"name\":\"{}\",\"ns\":\"{}\"}}", self.name.0, self.name_server.0)
601 fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
602 Ok(NS { name, name_server: read_wire_packet_name(&mut data, wire_packet)? })
604 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
605 out.extend_from_slice(&name_len(&self.name_server).to_be_bytes());
606 write_name(out, &self.name_server);