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;
10 use core::cmp::{self, Ordering};
14 /// A valid domain name.
16 /// It must end with a ".", be no longer than 255 bytes, consist of only printable ASCII
17 /// characters and each label may be no longer than 63 bytes.
18 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
19 pub struct Name(String);
21 /// Gets the underlying human-readable domain name
22 pub fn as_str(&self) -> &str { &self.0 }
24 impl core::ops::Deref for Name {
26 fn deref(&self) -> &str { &self.0 }
28 impl TryFrom<String> for Name {
30 fn try_from(s: String) -> Result<Name, ()> {
31 if s.is_empty() { return Err(()); }
32 if *s.as_bytes().last().unwrap_or(&0) != b"."[0] { return Err(()); }
33 if s.len() > 255 { return Err(()); }
34 if s.chars().any(|c| !c.is_ascii_graphic() && c != '.' && c != '-') { return Err(()); }
35 for label in s.split(".") {
36 if label.len() > 63 { return Err(()); }
42 impl TryFrom<&str> for Name {
44 fn try_from(s: &str) -> Result<Name, ()> {
45 Self::try_from(s.to_owned())
49 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
50 /// A supported Resource Record
52 /// Note that we only currently support a handful of RR types as needed to generate and validate
53 /// TXT or TLSA record proofs.
55 /// An IPv4 resource record
57 /// An IPv6 resource record
59 /// A name server resource record
61 /// A text resource record
63 /// A TLS Certificate Association resource record
65 /// A Canonical Name record
67 /// A DNS (Public) Key resource record
69 /// A Delegated Signer resource record
71 /// A Resource Record Signature record
75 /// Gets the name this record refers to.
76 pub fn name(&self) -> &Name {
78 RR::A(rr) => &rr.name,
79 RR::AAAA(rr) => &rr.name,
80 RR::NS(rr) => &rr.name,
81 RR::Txt(rr) => &rr.name,
82 RR::CName(rr) => &rr.name,
83 RR::TLSA(rr) => &rr.name,
84 RR::DnsKey(rr) => &rr.name,
85 RR::DS(rr) => &rr.name,
86 RR::RRSig(rr) => &rr.name,
92 RR::AAAA(_) => AAAA::TYPE,
93 RR::NS(_) => NS::TYPE,
94 RR::Txt(_) => Txt::TYPE,
95 RR::CName(_) => CName::TYPE,
96 RR::TLSA(_) => TLSA::TYPE,
97 RR::DnsKey(_) => DnsKey::TYPE,
98 RR::DS(_) => DS::TYPE,
99 RR::RRSig(_) => RRSig::TYPE,
102 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
104 RR::A(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
105 RR::AAAA(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
106 RR::NS(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
107 RR::Txt(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
108 RR::CName(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
109 RR::TLSA(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
110 RR::DnsKey(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
111 RR::DS(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
112 RR::RRSig(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
116 impl From<A> for RR { fn from(a: A) -> RR { RR::A(a) } }
117 impl From<AAAA> for RR { fn from(aaaa: AAAA) -> RR { RR::AAAA(aaaa) } }
118 impl From<NS> for RR { fn from(ns: NS) -> RR { RR::NS(ns) } }
119 impl From<Txt> for RR { fn from(txt: Txt) -> RR { RR::Txt(txt) } }
120 impl From<CName> for RR { fn from(cname: CName) -> RR { RR::CName(cname) } }
121 impl From<TLSA> for RR { fn from(tlsa: TLSA) -> RR { RR::TLSA(tlsa) } }
122 impl From<DnsKey> for RR { fn from(dnskey: DnsKey) -> RR { RR::DnsKey(dnskey) } }
123 impl From<DS> for RR { fn from(ds: DS) -> RR { RR::DS(ds) } }
124 impl From<RRSig> for RR { fn from(rrsig: RRSig) -> RR { RR::RRSig(rrsig) } }
126 pub(crate) trait StaticRecord : Ord + Sized {
127 // http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4
129 fn name(&self) -> &Name;
130 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>);
131 fn read_from_data(name: Name, data: &[u8], wire_packet: &[u8]) -> Result<Self, ()>;
133 /// A trait describing a resource record (including the [`RR`] enum).
134 pub trait Record : Ord {
135 /// The resource record type, as maintained by IANA.
137 /// Current assignments can be found at
138 /// <http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4>
140 /// The name this record is at.
141 fn name(&self) -> &Name;
142 /// Writes the data of this record, prefixed by a u16 length, to the given `Vec`.
143 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>);
145 impl<RR: StaticRecord> Record for RR {
146 fn ty(&self) -> u16 { RR::TYPE }
147 fn name(&self) -> &Name { RR::name(self) }
148 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
149 RR::write_u16_len_prefixed_data(self, out)
153 fn ty(&self) -> u16 { self.ty() }
154 fn name(&self) -> &Name { self.name() }
155 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
156 self.write_u16_len_prefixed_data(out)
160 #[derive(Debug, Clone, PartialEq, Eq, Ord)]
161 /// A text resource record, containing arbitrary text data
163 /// The name this record is at.
165 /// The text record itself.
167 /// While this is generally UTF-8-valid, there is no specific requirement that it be, and thus
168 /// is an arbitrary series of bytes here.
171 impl PartialOrd for Txt {
172 fn partial_cmp(&self, o: &Txt) -> Option<Ordering> {
173 Some(self.name.cmp(&o.name)
175 // Compare in wire encoding form, i.e. compare in 255-byte chunks
176 for i in 1..(self.data.len() / 255) + 2 {
177 let start = (i - 1)*255;
178 let self_len = cmp::min(i * 255, self.data.len());
179 let o_len = cmp::min(i * 255, o.data.len());
180 let slice_cmp = self_len.cmp(&o_len)
181 .then_with(|| self.data[start..self_len].cmp(&o.data[start..o_len]));
182 if !slice_cmp.is_eq() { return slice_cmp; }
188 impl StaticRecord for Txt {
189 const TYPE: u16 = 16;
190 fn name(&self) -> &Name { &self.name }
191 fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
192 let mut parsed_data = Vec::with_capacity(data.len() - 1);
193 while !data.is_empty() {
194 let len = read_u8(&mut data)? as usize;
195 if data.len() < len { return Err(()); }
196 parsed_data.extend_from_slice(&data[..len]);
199 Ok(Txt { name, data: parsed_data })
201 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
202 let len = (self.data.len() + (self.data.len() + 254) / 255) as u16;
203 out.extend_from_slice(&len.to_be_bytes());
205 let mut data_write = &self.data[..];
206 out.extend_from_slice(&[data_write.len().try_into().unwrap_or(255)]);
207 while !data_write.is_empty() {
208 let split_pos = core::cmp::min(255, data_write.len());
209 out.extend_from_slice(&data_write[..split_pos]);
210 data_write = &data_write[split_pos..];
211 if !data_write.is_empty() {
212 out.extend_from_slice(&[data_write.len().try_into().unwrap_or(255)]);
218 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
219 /// A TLS Certificate Association resource record containing information about the TLS certificate
220 /// which should be expected when communicating with the host at the given name.
222 /// See <https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities#TLSA_RR> for more
225 /// The name this record is at.
227 /// The type of constraint on the TLS certificate(s) used which should be enforced by this
230 /// Whether to match on the full certificate, or only the public key.
232 /// The type of data included which is used to match the TLS certificate(s).
234 /// The certificate data or hash of the certificate data itself.
237 impl StaticRecord for TLSA {
238 const TYPE: u16 = 52;
239 fn name(&self) -> &Name { &self.name }
240 fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
242 name, cert_usage: read_u8(&mut data)?, selector: read_u8(&mut data)?,
243 data_ty: read_u8(&mut data)?, data: data.to_vec(),
246 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
247 let len = 3 + self.data.len();
248 out.extend_from_slice(&(len as u16).to_be_bytes());
249 out.extend_from_slice(&[self.cert_usage, self.selector, self.data_ty]);
250 out.extend_from_slice(&self.data);
254 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
255 /// A Canonical Name resource record, referring all queries for this name to another name.
257 /// The name this record is at.
259 /// The canonical name.
261 /// A resolver should use this name when looking up any further records for [`Self::name`].
262 pub canonical_name: Name,
264 impl StaticRecord for CName {
266 fn name(&self) -> &Name { &self.name }
267 fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
268 Ok(CName { name, canonical_name: read_wire_packet_name(&mut data, wire_packet)? })
270 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
271 let len: u16 = name_len(&self.canonical_name);
272 out.extend_from_slice(&len.to_be_bytes());
273 write_name(out, &self.canonical_name);
277 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
278 /// A public key resource record which can be used to validate [`RRSig`]s.
280 /// The name this record is at.
282 /// Flags which constrain the usage of this public key.
284 /// The protocol this key is used for (protocol `3` is DNSSEC).
286 /// The algorithm which this public key uses to sign data.
288 /// The public key itself.
291 impl StaticRecord for DnsKey {
292 const TYPE: u16 = 48;
293 fn name(&self) -> &Name { &self.name }
294 fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
296 name, flags: read_u16(&mut data)?, protocol: read_u8(&mut data)?,
297 alg: read_u8(&mut data)?, pubkey: data.to_vec(),
300 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
301 let len = 2 + 1 + 1 + self.pubkey.len();
302 out.extend_from_slice(&(len as u16).to_be_bytes());
303 out.extend_from_slice(&self.flags.to_be_bytes());
304 out.extend_from_slice(&self.protocol.to_be_bytes());
305 out.extend_from_slice(&self.alg.to_be_bytes());
306 out.extend_from_slice(&self.pubkey);
310 /// A short (non-cryptographic) digest which can be used to refer to this [`DnsKey`].
311 pub fn key_tag(&self) -> u16 {
312 let mut res = u32::from(self.flags);
313 res += u32::from(self.protocol) << 8;
314 res += u32::from(self.alg);
315 for (idx, b) in self.pubkey.iter().enumerate() {
317 res += u32::from(*b) << 8;
319 res += u32::from(*b);
322 res += (res >> 16) & 0xffff;
323 (res & 0xffff) as u16
327 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
328 /// A Delegation Signer resource record which indicates that some alternative [`DnsKey`] can sign
329 /// for records in the zone which matches [`DS::name`].
331 /// The name this record is at.
333 /// This is also the zone that a [`DnsKey`] which matches the [`Self::digest`] can sign for.
335 /// A short tag which describes the matching [`DnsKey`].
337 /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which is referred to by this
340 /// The algorithm which the [`DnsKey`] referred to by this [`DS`] uses.
342 /// This matches the [`DnsKey::alg`] field in the referred-to [`DnsKey`].
344 /// The type of digest used to hash the referred-to [`DnsKey`].
346 /// The digest itself.
349 impl StaticRecord for DS {
350 const TYPE: u16 = 43;
351 fn name(&self) -> &Name { &self.name }
352 fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
354 name, key_tag: read_u16(&mut data)?, alg: read_u8(&mut data)?,
355 digest_type: read_u8(&mut data)?, digest: data.to_vec(),
358 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
359 let len = 2 + 1 + 1 + self.digest.len();
360 out.extend_from_slice(&(len as u16).to_be_bytes());
361 out.extend_from_slice(&self.key_tag.to_be_bytes());
362 out.extend_from_slice(&self.alg.to_be_bytes());
363 out.extend_from_slice(&self.digest_type.to_be_bytes());
364 out.extend_from_slice(&self.digest);
368 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
369 /// A Resource Record (set) Signature resource record. This contains a signature over all the
370 /// resources records of the given type at the given name.
372 /// The name this record is at.
374 /// This is also the name of any records which this signature is covering (ignoring wildcards).
376 /// The resource record type which this [`RRSig`] is signing.
378 /// All resources records of this type at the same name as [`Self::name`] must be signed by
381 /// The algorithm which is being used to sign.
383 /// This must match the [`DnsKey::alg`] field in the [`DnsKey`] being used to sign.
385 /// The number of labels in the name of the records that this signature is signing.
387 /// If this is less than the number of labels in [`Self::name`], this signature is covering a
390 /// The TTL of the records which this [`RRSig`] is signing.
392 /// The expiration (as a UNIX timestamp) of this signature.
394 /// The time (as a UNIX timestamp) at which this signature becomes valid.
396 /// A short tag which describes the matching [`DnsKey`].
398 /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which created this signature.
400 /// The [`DnsKey::name`] in the [`DnsKey`] which created this signature.
402 /// This must be a parent of the [`Self::name`].
404 /// The signature itself.
405 pub signature: Vec<u8>,
407 impl StaticRecord for RRSig {
408 const TYPE: u16 = 46;
409 fn name(&self) -> &Name { &self.name }
410 fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
412 name, ty: read_u16(&mut data)?, alg: read_u8(&mut data)?,
413 labels: read_u8(&mut data)?, orig_ttl: read_u32(&mut data)?,
414 expiration: read_u32(&mut data)?, inception: read_u32(&mut data)?,
415 key_tag: read_u16(&mut data)?,
416 key_name: read_wire_packet_name(&mut data, wire_packet)?,
417 signature: data.to_vec(),
420 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
421 let len = 2 + 1 + 1 + 4*3 + 2 + name_len(&self.key_name) + self.signature.len() as u16;
422 out.extend_from_slice(&len.to_be_bytes());
423 out.extend_from_slice(&self.ty.to_be_bytes());
424 out.extend_from_slice(&self.alg.to_be_bytes());
425 out.extend_from_slice(&self.labels.to_be_bytes());
426 out.extend_from_slice(&self.orig_ttl.to_be_bytes());
427 out.extend_from_slice(&self.expiration.to_be_bytes());
428 out.extend_from_slice(&self.inception.to_be_bytes());
429 out.extend_from_slice(&self.key_tag.to_be_bytes());
430 write_name(out, &self.key_name);
431 out.extend_from_slice(&self.signature);
435 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
436 /// An IPv4 Address resource record
438 /// The name this record is at.
440 /// The bytes of the IPv4 address.
441 pub address: [u8; 4],
443 impl StaticRecord for A {
445 fn name(&self) -> &Name { &self.name }
446 fn read_from_data(name: Name, data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
447 if data.len() != 4 { return Err(()); }
448 let mut address = [0; 4];
449 address.copy_from_slice(&data);
450 Ok(A { name, address })
452 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
453 out.extend_from_slice(&4u16.to_be_bytes());
454 out.extend_from_slice(&self.address);
458 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
459 /// An IPv6 Address resource record
461 /// The name this record is at.
463 /// The bytes of the IPv6 address.
464 pub address: [u8; 16],
466 impl StaticRecord for AAAA {
467 const TYPE: u16 = 28;
468 fn name(&self) -> &Name { &self.name }
469 fn read_from_data(name: Name, data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
470 if data.len() != 16 { return Err(()); }
471 let mut address = [0; 16];
472 address.copy_from_slice(&data);
473 Ok(AAAA { name, address })
475 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
476 out.extend_from_slice(&16u16.to_be_bytes());
477 out.extend_from_slice(&self.address);
481 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
482 /// A Name Server resource record, which indicates the server responsible for handling queries for
485 /// The name this record is at.
487 /// This is also the zone which the server at [`Self::name_server`] is responsible for handling
490 /// The name of the server which is responsible for handling queries for the [`Self::name`]
492 pub name_server: Name,
494 impl StaticRecord for NS {
496 fn name(&self) -> &Name { &self.name }
497 fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
498 Ok(NS { name, name_server: read_wire_packet_name(&mut data, wire_packet)? })
500 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
501 out.extend_from_slice(&name_len(&self.name_server).to_be_bytes());
502 write_name(out, &self.name_server);