fbe8f65a5223b76e75b8a37e379256c36485ee69
[dnssec-prover] / src / rr.rs
1 //! Resource Records are the fundamental type in the DNS - individual records mapping a name to
2 //! some data.
3 //!
4 //! This module holds structs and utilities for the Resource Records supported by this crate.
5
6 use alloc::vec::Vec;
7 use alloc::string::String;
8 use alloc::borrow::ToOwned;
9 use alloc::format;
10
11 use core::cmp::{self, Ordering};
12 use core::fmt;
13 use core::fmt::Write;
14
15 use crate::ser::*;
16
17 /// A valid domain name.
18 ///
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);
23 impl Name {
24         /// Gets the underlying human-readable domain name
25         pub fn as_str(&self) -> &str { &self.0 }
26         /// Gets the number of labels in this name
27         pub fn labels(&self) -> u8 {
28                 if self.as_str() == "." {
29                         0
30                 } else {
31                         self.as_str().chars().filter(|c| *c == '.').count() as u8
32                 }
33         }
34         /// Gets a string containing the last `n` labels in this [`Name`] (which is also a valid name).
35         pub fn trailing_n_labels(&self, n: u8) -> Option<&str> {
36                 let labels = self.labels();
37                 if n > labels {
38                         None
39                 } else if n == labels {
40                         Some(self.as_str())
41                 } else if n == 0 {
42                         Some(".")
43                 } else {
44                         self.as_str().splitn(labels as usize - n as usize + 1, ".").last()
45                 }
46         }
47 }
48 impl core::ops::Deref for Name {
49         type Target = str;
50         fn deref(&self) -> &str { &self.0 }
51 }
52 impl fmt::Display for Name {
53         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
54                 self.0.fmt(f)
55         }
56 }
57 impl TryFrom<String> for Name {
58         type Error = ();
59         fn try_from(s: String) -> Result<Name, ()> {
60                 if s.is_empty() { return Err(()); }
61                 if *s.as_bytes().last().unwrap_or(&0) != b"."[0] { return Err(()); }
62                 if s.len() > 255 { return Err(()); }
63                 if s.chars().any(|c| !c.is_ascii_graphic() || c == '"') { return Err(()); }
64                 for label in s.split(".") {
65                         if label.len() > 63 { return Err(()); }
66                 }
67
68                 Ok(Name(s.to_ascii_lowercase()))
69         }
70 }
71 impl TryFrom<&str> for Name {
72         type Error = ();
73         fn try_from(s: &str) -> Result<Name, ()> {
74                 Self::try_from(s.to_owned())
75         }
76 }
77
78 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
79 /// A supported Resource Record
80 ///
81 /// Note that we only currently support a handful of RR types as needed to generate and validate
82 /// TXT or TLSA record proofs.
83 pub enum RR {
84         /// An IPv4 resource record
85         A(A),
86         /// An IPv6 resource record
87         AAAA(AAAA),
88         /// A name server resource record
89         NS(NS),
90         /// A text resource record
91         Txt(Txt),
92         /// A TLS Certificate Association resource record
93         TLSA(TLSA),
94         /// A Canonical Name record
95         CName(CName),
96         /// A Delegation Name record
97         DName(DName),
98         /// A DNS (Public) Key resource record
99         DnsKey(DnsKey),
100         /// A Delegated Signer resource record
101         DS(DS),
102         /// A Resource Record Signature record
103         RRSig(RRSig),
104         /// A Next Secure Record record
105         NSec(NSec),
106         /// A Next Secure Record version 3 record
107         NSec3(NSec3),
108 }
109 impl RR {
110         /// Gets the name this record refers to.
111         pub fn name(&self) -> &Name {
112                 match self {
113                         RR::A(rr) => &rr.name,
114                         RR::AAAA(rr) => &rr.name,
115                         RR::NS(rr) => &rr.name,
116                         RR::Txt(rr) => &rr.name,
117                         RR::CName(rr) => &rr.name,
118                         RR::DName(rr) => &rr.name,
119                         RR::TLSA(rr) => &rr.name,
120                         RR::DnsKey(rr) => &rr.name,
121                         RR::DS(rr) => &rr.name,
122                         RR::RRSig(rr) => &rr.name,
123                         RR::NSec(rr) => &rr.name,
124                         RR::NSec3(rr) => &rr.name,
125                 }
126         }
127         /// Gets a JSON encoding of this record
128         pub fn json(&self) -> String {
129                 match self {
130                         RR::A(rr) => StaticRecord::json(rr),
131                         RR::AAAA(rr) => StaticRecord::json(rr),
132                         RR::NS(rr) => StaticRecord::json(rr),
133                         RR::Txt(rr) => StaticRecord::json(rr),
134                         RR::CName(rr) => StaticRecord::json(rr),
135                         RR::DName(rr) => StaticRecord::json(rr),
136                         RR::TLSA(rr) => StaticRecord::json(rr),
137                         RR::DnsKey(rr) => StaticRecord::json(rr),
138                         RR::DS(rr) => StaticRecord::json(rr),
139                         RR::RRSig(rr) => StaticRecord::json(rr),
140                         RR::NSec(rr) => StaticRecord::json(rr),
141                         RR::NSec3(rr) => StaticRecord::json(rr),
142                 }
143         }
144         fn ty(&self) -> u16 {
145                 match self {
146                         RR::A(_) => A::TYPE,
147                         RR::AAAA(_) => AAAA::TYPE,
148                         RR::NS(_) => NS::TYPE,
149                         RR::Txt(_) => Txt::TYPE,
150                         RR::CName(_) => CName::TYPE,
151                         RR::DName(_) => DName::TYPE,
152                         RR::TLSA(_) => TLSA::TYPE,
153                         RR::DnsKey(_) => DnsKey::TYPE,
154                         RR::DS(_) => DS::TYPE,
155                         RR::RRSig(_) => RRSig::TYPE,
156                         RR::NSec(_) => NSec::TYPE,
157                         RR::NSec3(_) => NSec3::TYPE,
158                 }
159         }
160         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
161                 match self {
162                         RR::A(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
163                         RR::AAAA(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
164                         RR::NS(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
165                         RR::Txt(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
166                         RR::CName(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
167                         RR::DName(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
168                         RR::TLSA(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
169                         RR::DnsKey(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
170                         RR::DS(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
171                         RR::RRSig(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
172                         RR::NSec(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
173                         RR::NSec3(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
174                 }
175         }
176         fn ty_to_rr_name(ty: u16) -> Option<&'static str> {
177                 match ty {
178                         A::TYPE => Some("A"),
179                         AAAA::TYPE => Some("AAAA"),
180                         NS::TYPE => Some("NS"),
181                         Txt::TYPE => Some("TXT"),
182                         CName::TYPE => Some("CNAME"),
183                         DName::TYPE => Some("DNAME"),
184                         TLSA::TYPE => Some("TLSA"),
185                         DnsKey::TYPE => Some("DNSKEY"),
186                         DS::TYPE => Some("DS"),
187                         RRSig::TYPE => Some("RRSIG"),
188                         NSec::TYPE => Some("NSEC"),
189                         NSec3::TYPE => Some("NSEC3"),
190                         _ => None,
191                 }
192         }
193 }
194 impl From<A> for RR { fn from(a: A) -> RR { RR::A(a) } }
195 impl From<AAAA> for RR { fn from(aaaa: AAAA) -> RR { RR::AAAA(aaaa) } }
196 impl From<NS> for RR { fn from(ns: NS) -> RR { RR::NS(ns) } }
197 impl From<Txt> for RR { fn from(txt: Txt) -> RR { RR::Txt(txt) } }
198 impl From<CName> for RR { fn from(cname: CName) -> RR { RR::CName(cname) } }
199 impl From<DName> for RR { fn from(cname: DName) -> RR { RR::DName(cname) } }
200 impl From<TLSA> for RR { fn from(tlsa: TLSA) -> RR { RR::TLSA(tlsa) } }
201 impl From<DnsKey> for RR { fn from(dnskey: DnsKey) -> RR { RR::DnsKey(dnskey) } }
202 impl From<DS> for RR { fn from(ds: DS) -> RR { RR::DS(ds) } }
203 impl From<RRSig> for RR { fn from(rrsig: RRSig) -> RR { RR::RRSig(rrsig) } }
204 impl From<NSec> for RR { fn from(nsec: NSec) -> RR { RR::NSec(nsec) } }
205 impl From<NSec3> for RR { fn from(nsec3: NSec3) -> RR { RR::NSec3(nsec3) } }
206
207 pub(crate) trait StaticRecord : Ord + Sized {
208         // http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4
209         const TYPE: u16;
210         fn name(&self) -> &Name;
211         fn json(&self) -> String;
212         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>);
213         fn read_from_data(name: Name, data: &[u8], wire_packet: &[u8]) -> Result<Self, ()>;
214 }
215 /// A trait describing a resource record (including the [`RR`] enum).
216 pub trait Record : Ord {
217         /// The resource record type, as maintained by IANA.
218         ///
219         /// Current assignments can be found at
220         /// <http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4>
221         fn ty(&self) -> u16;
222         /// The name this record is at.
223         fn name(&self) -> &Name;
224         /// Gets a JSON encoding of this record.
225         fn json(&self) -> String;
226         /// Writes the data of this record, prefixed by a u16 length, to the given `Vec`.
227         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>);
228 }
229 impl<RR: StaticRecord> Record for RR {
230         fn ty(&self) -> u16 { RR::TYPE }
231         fn name(&self) -> &Name { RR::name(self) }
232         fn json(&self) -> String { RR::json(self) }
233         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
234                 RR::write_u16_len_prefixed_data(self, out)
235         }
236 }
237 impl Record for RR {
238         fn ty(&self) -> u16 { self.ty() }
239         fn name(&self) -> &Name { self.name() }
240         fn json(&self) -> String { self.json() }
241         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
242                 self.write_u16_len_prefixed_data(out)
243         }
244 }
245
246 #[derive(Debug, Clone, PartialEq, Eq, Ord)]
247 /// A text resource record, containing arbitrary text data
248 pub struct Txt {
249         /// The name this record is at.
250         pub name: Name,
251         /// The text record itself.
252         ///
253         /// While this is generally UTF-8-valid, there is no specific requirement that it be, and thus
254         /// is an arbitrary series of bytes here.
255         pub data: Vec<u8>,
256 }
257 /// The wire type for TXT records
258 pub const TXT_TYPE: u16 = 16;
259 impl PartialOrd for Txt {
260         fn partial_cmp(&self, o: &Txt) -> Option<Ordering> {
261                 Some(self.name.cmp(&o.name)
262                         .then_with(|| {
263                                 // Compare in wire encoding form, i.e. compare in 255-byte chunks
264                                 for i in 1..(self.data.len() / 255) + 2 {
265                                         let start = (i - 1)*255;
266                                         let self_len = cmp::min(i * 255, self.data.len());
267                                         let o_len = cmp::min(i * 255, o.data.len());
268                                         let slice_cmp = self_len.cmp(&o_len)
269                                                 .then_with(|| self.data[start..self_len].cmp(&o.data[start..o_len]));
270                                         if !slice_cmp.is_eq() { return slice_cmp; }
271                                 }
272                                 Ordering::Equal
273                         }))
274         }
275 }
276 impl StaticRecord for Txt {
277         const TYPE: u16 = TXT_TYPE;
278         fn name(&self) -> &Name { &self.name }
279         fn json(&self) -> String {
280                 if let Ok(s) = core::str::from_utf8(&self.data) {
281                         if s.chars().all(|c| !c.is_control() && c != '"' && c != '\\') {
282                                 return format!("{{\"type\":\"txt\",\"name\":\"{}\",\"contents\":\"{}\"}}", self.name.0, s);
283                         }
284                 }
285                 format!("{{\"type\":\"txt\",\"name\":\"{}\",\"contents\":{:?}}}", self.name.0, &self.data[..])
286         }
287         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
288                 let mut parsed_data = Vec::with_capacity(data.len().saturating_sub(1));
289                 while !data.is_empty() {
290                         let len = read_u8(&mut data)? as usize;
291                         if data.len() < len { return Err(()); }
292                         parsed_data.extend_from_slice(&data[..len]);
293                         data = &data[len..];
294                 }
295                 debug_assert!(data.is_empty());
296                 Ok(Txt { name, data: parsed_data })
297         }
298         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
299                 let len = (self.data.len() + (self.data.len() + 254) / 255) as u16;
300                 out.extend_from_slice(&len.to_be_bytes());
301
302                 let mut data_write = &self.data[..];
303                 out.extend_from_slice(&[data_write.len().try_into().unwrap_or(255)]);
304                 while !data_write.is_empty() {
305                         let split_pos = core::cmp::min(255, data_write.len());
306                         out.extend_from_slice(&data_write[..split_pos]);
307                         data_write = &data_write[split_pos..];
308                         if !data_write.is_empty() {
309                                 out.extend_from_slice(&[data_write.len().try_into().unwrap_or(255)]);
310                         }
311                 }
312         }
313 }
314
315 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
316 /// A TLS Certificate Association resource record containing information about the TLS certificate
317 /// which should be expected when communicating with the host at the given name.
318 ///
319 /// See <https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities#TLSA_RR> for more
320 /// info.
321 pub struct TLSA {
322         /// The name this record is at.
323         pub name: Name,
324         /// The type of constraint on the TLS certificate(s) used which should be enforced by this
325         /// record.
326         pub cert_usage: u8,
327         /// Whether to match on the full certificate, or only the public key.
328         pub selector: u8,
329         /// The type of data included which is used to match the TLS certificate(s).
330         pub data_ty: u8,
331         /// The certificate data or hash of the certificate data itself.
332         pub data: Vec<u8>,
333 }
334 /// The wire type for TLSA records
335 pub const TLSA_TYPE: u16 = 52;
336 impl StaticRecord for TLSA {
337         const TYPE: u16 = TLSA_TYPE;
338         fn name(&self) -> &Name { &self.name }
339         fn json(&self) -> String {
340                 let mut out = String::with_capacity(128+self.data.len()*2);
341                 write!(&mut out,
342                         "{{\"type\":\"tlsa\",\"name\":\"{}\",\"usage\":{},\"selector\":{},\"data_ty\":{},\"data\":\"",
343                         self.name.0, self.cert_usage, self.selector, self.data_ty
344                 ).expect("Write to a String shouldn't fail");
345                 for c in self.data.iter() {
346                         write!(&mut out, "{:02X}", c)
347                                 .expect("Write to a String shouldn't fail");
348                 }
349                 out += "\"}";
350                 out
351         }
352         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
353                 Ok(TLSA {
354                         name, cert_usage: read_u8(&mut data)?, selector: read_u8(&mut data)?,
355                         data_ty: read_u8(&mut data)?, data: data.to_vec(),
356                 })
357         }
358         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
359                 let len = 3 + self.data.len();
360                 out.extend_from_slice(&(len as u16).to_be_bytes());
361                 out.extend_from_slice(&[self.cert_usage, self.selector, self.data_ty]);
362                 out.extend_from_slice(&self.data);
363         }
364 }
365
366 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
367 /// A Canonical Name resource record, referring all queries for this name to another name.
368 pub struct CName {
369         /// The name this record is at.
370         pub name: Name,
371         /// The canonical name.
372         ///
373         /// A resolver should use this name when looking up any further records for [`self.name`].
374         pub canonical_name: Name,
375 }
376 impl StaticRecord for CName {
377         const TYPE: u16 = 5;
378         fn name(&self) -> &Name { &self.name }
379         fn json(&self) -> String {
380                 format!("{{\"type\":\"cname\",\"name\":\"{}\",\"canonical_name\":\"{}\"}}",
381                         self.name.0, self.canonical_name.0)
382         }
383         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
384                 let res = CName { name, canonical_name: read_wire_packet_name(&mut data, wire_packet)? };
385                 debug_assert!(data.is_empty());
386                 Ok(res)
387         }
388         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
389                 let len: u16 = name_len(&self.canonical_name);
390                 out.extend_from_slice(&len.to_be_bytes());
391                 write_name(out, &self.canonical_name);
392         }
393 }
394
395 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
396 /// A Delegation Name resource record, referring all queries for subdomains of this name to another
397 /// subtree of the DNS.
398 pub struct DName {
399         /// The name this record is at.
400         pub name: Name,
401         /// The delegation name.
402         ///
403         /// A resolver should use this domain name tree when looking up any further records for
404         /// subdomains of [`self.name`].
405         pub delegation_name: Name,
406 }
407 impl StaticRecord for DName {
408         const TYPE: u16 = 39;
409         fn name(&self) -> &Name { &self.name }
410         fn json(&self) -> String {
411                 format!("{{\"type\":\"dname\",\"name\":\"{}\",\"delegation_name\":\"{}\"}}",
412                         self.name.0, self.delegation_name.0)
413         }
414         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
415                 let res = DName { name, delegation_name: read_wire_packet_name(&mut data, wire_packet)? };
416                 debug_assert!(data.is_empty());
417                 Ok(res)
418         }
419         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
420                 let len: u16 = name_len(&self.delegation_name);
421                 out.extend_from_slice(&len.to_be_bytes());
422                 write_name(out, &self.delegation_name);
423         }
424 }
425
426
427 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
428 /// A public key resource record which can be used to validate [`RRSig`]s.
429 pub struct DnsKey {
430         /// The name this record is at.
431         pub name: Name,
432         /// Flags which constrain the usage of this public key.
433         pub flags: u16,
434         /// The protocol this key is used for (protocol `3` is DNSSEC). 
435         pub protocol: u8,
436         /// The algorithm which this public key uses to sign data.
437         pub alg: u8,
438         /// The public key itself.
439         pub pubkey: Vec<u8>,
440 }
441 impl StaticRecord for DnsKey {
442         const TYPE: u16 = 48;
443         fn name(&self) -> &Name { &self.name }
444         fn json(&self) -> String {
445                 let mut out = String::with_capacity(128+self.pubkey.len()*2);
446                 write!(&mut out,
447                         "{{\"type\":\"dnskey\",\"name\":\"{}\",\"flags\":{},\"protocol\":{},\"alg\":{},\"pubkey\":\"",
448                         self.name.0, self.flags, self.protocol, self.alg
449                 ).expect("Write to a String shouldn't fail");
450                 for c in self.pubkey.iter() {
451                         write!(&mut out, "{:02X}", c)
452                                 .expect("Write to a String shouldn't fail");
453                 }
454                 out += "\"}";
455                 out
456         }
457         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
458                 Ok(DnsKey {
459                         name, flags: read_u16(&mut data)?, protocol: read_u8(&mut data)?,
460                         alg: read_u8(&mut data)?, pubkey: data.to_vec(),
461                 })
462         }
463         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
464                 let len = 2 + 1 + 1 + self.pubkey.len();
465                 out.extend_from_slice(&(len as u16).to_be_bytes());
466                 out.extend_from_slice(&self.flags.to_be_bytes());
467                 out.extend_from_slice(&self.protocol.to_be_bytes());
468                 out.extend_from_slice(&self.alg.to_be_bytes());
469                 out.extend_from_slice(&self.pubkey);
470         }
471 }
472 impl DnsKey {
473         /// A short (non-cryptographic) digest which can be used to refer to this [`DnsKey`].
474         pub fn key_tag(&self) -> u16 {
475                 let mut res = u32::from(self.flags);
476                 res += u32::from(self.protocol) << 8;
477                 res += u32::from(self.alg);
478                 for (idx, b) in self.pubkey.iter().enumerate() {
479                         if idx % 2 == 0 {
480                                 res += u32::from(*b) << 8;
481                         } else {
482                                 res += u32::from(*b);
483                         }
484                 }
485                 res += (res >> 16) & 0xffff;
486                 (res & 0xffff) as u16
487         }
488 }
489
490 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
491 /// A Delegation Signer resource record which indicates that some alternative [`DnsKey`] can sign
492 /// for records in the zone which matches [`self.name`].
493 pub struct DS {
494         /// The name this record is at.
495         ///
496         /// This is also the zone that a [`DnsKey`] which matches the [`Self::digest`] can sign for.
497         pub name: Name,
498         /// A short tag which describes the matching [`DnsKey`].
499         ///
500         /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which is referred to by this
501         /// [`DS`].
502         pub key_tag: u16,
503         /// The algorithm which the [`DnsKey`] referred to by this [`DS`] uses.
504         ///
505         /// This matches the [`DnsKey::alg`] field in the referred-to [`DnsKey`].
506         pub alg: u8,
507         /// The type of digest used to hash the referred-to [`DnsKey`].
508         pub digest_type: u8,
509         /// The digest itself.
510         pub digest: Vec<u8>,
511 }
512 impl StaticRecord for DS {
513         const TYPE: u16 = 43;
514         fn name(&self) -> &Name { &self.name }
515         fn json(&self) -> String {
516                 let mut out = String::with_capacity(128+self.digest.len()*2);
517                 write!(&mut out,
518                         "{{\"type\":\"ds\",\"name\":\"{}\",\"key_tag\":{},\"alg\":{},\"digest_type\":{},\"digest\":\"",
519                         self.name.0, self.key_tag, self.alg, self.digest_type
520                 ).expect("Write to a String shouldn't fail");
521                 for c in self.digest.iter() {
522                         write!(&mut out, "{:02X}", c)
523                                 .expect("Write to a String shouldn't fail");
524                 }
525                 out += "\"}";
526                 out
527         }
528         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
529                 Ok(DS {
530                         name, key_tag: read_u16(&mut data)?, alg: read_u8(&mut data)?,
531                         digest_type: read_u8(&mut data)?, digest: data.to_vec(),
532                 })
533         }
534         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
535                 let len = 2 + 1 + 1 + self.digest.len();
536                 out.extend_from_slice(&(len as u16).to_be_bytes());
537                 out.extend_from_slice(&self.key_tag.to_be_bytes());
538                 out.extend_from_slice(&self.alg.to_be_bytes());
539                 out.extend_from_slice(&self.digest_type.to_be_bytes());
540                 out.extend_from_slice(&self.digest);
541         }
542 }
543
544 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
545 /// A Resource Record (set) Signature resource record. This contains a signature over all the
546 /// resources records of the given type at the given name.
547 pub struct RRSig {
548         /// The name this record is at.
549         ///
550         /// This is also the name of any records which this signature is covering (ignoring wildcards).
551         pub name: Name,
552         /// The resource record type which this [`RRSig`] is signing.
553         ///
554         /// All resources records of this type at the same name as [`self.name`] must be signed by
555         /// this [`RRSig`].
556         pub ty: u16,
557         /// The algorithm which is being used to sign.
558         ///
559         /// This must match the [`DnsKey::alg`] field in the [`DnsKey`] being used to sign.
560         pub alg: u8,
561         /// The number of labels in the name of the records that this signature is signing.
562         ///
563         /// If this is less than the number of labels in [`self.name`], this signature is covering a
564         /// wildcard entry.
565         pub labels: u8,
566         /// The TTL of the records which this [`RRSig`] is signing.
567         pub orig_ttl: u32,
568         /// The expiration (as a UNIX timestamp) of this signature.
569         pub expiration: u32,
570         /// The time (as a UNIX timestamp) at which this signature becomes valid.
571         pub inception: u32,
572         /// A short tag which describes the matching [`DnsKey`].
573         ///
574         /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which created this signature.
575         pub key_tag: u16,
576         /// The [`DnsKey::name`] in the [`DnsKey`] which created this signature.
577         ///
578         /// This must be a parent of [`self.name`].
579         ///
580         /// [`DnsKey::name`]: Record::name
581         // We'd like to just link to the `DnsKey` member variable called `name`, but there doesn't
582         // appear to be a way to actually do that, so instead we have to link to the trait method.
583         pub key_name: Name,
584         /// The signature itself.
585         pub signature: Vec<u8>,
586 }
587 impl StaticRecord for RRSig {
588         const TYPE: u16 = 46;
589         fn name(&self) -> &Name { &self.name }
590         fn json(&self) -> String {
591                 let mut out = String::with_capacity(256 + self.signature.len()*2);
592                 write!(&mut out,
593                         "{{\"type\":\"ds\",\"name\":\"{}\",\"signed_record_type\":{},\"alg\":{},\"signed_labels\":{},\"orig_ttl\":{},\"expiration\"{},\"inception\":{},\"key_tag\":{},\"key_name\":\"{}\",\"signature\":\"",
594                         self.name.0, self.ty, self.alg, self.labels, self.orig_ttl, self.expiration, self.inception, self.key_tag, self.key_name.0
595                 ).expect("Write to a String shouldn't fail");
596                 for c in self.signature.iter() {
597                         write!(&mut out, "{:02X}", c)
598                                 .expect("Write to a String shouldn't fail");
599                 }
600                 out += "\"}";
601                 out
602         }
603         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
604                 Ok(RRSig {
605                         name, ty: read_u16(&mut data)?, alg: read_u8(&mut data)?,
606                         labels: read_u8(&mut data)?, orig_ttl: read_u32(&mut data)?,
607                         expiration: read_u32(&mut data)?, inception: read_u32(&mut data)?,
608                         key_tag: read_u16(&mut data)?,
609                         key_name: read_wire_packet_name(&mut data, wire_packet)?,
610                         signature: data.to_vec(),
611                 })
612         }
613         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
614                 let len = 2 + 1 + 1 + 4*3 + 2 + name_len(&self.key_name) + self.signature.len() as u16;
615                 out.extend_from_slice(&len.to_be_bytes());
616                 out.extend_from_slice(&self.ty.to_be_bytes());
617                 out.extend_from_slice(&self.alg.to_be_bytes());
618                 out.extend_from_slice(&self.labels.to_be_bytes());
619                 out.extend_from_slice(&self.orig_ttl.to_be_bytes());
620                 out.extend_from_slice(&self.expiration.to_be_bytes());
621                 out.extend_from_slice(&self.inception.to_be_bytes());
622                 out.extend_from_slice(&self.key_tag.to_be_bytes());
623                 write_name(out, &self.key_name);
624                 out.extend_from_slice(&self.signature);
625         }
626 }
627
628 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
629 /// A mask used in [`NSec`] and [`NSec3`] records which indicates the resource record types which
630 /// exist at the (hash of the) name described in [`Record::name`].
631 pub struct NSecTypeMask([u8; 8192]);
632 impl NSecTypeMask {
633         /// Constructs a new, empty, type mask.
634         pub fn new() -> Self { Self([0; 8192]) }
635         /// Builds a new type mask with the given types set
636         pub fn from_types(types: &[u16]) -> Self {
637                 let mut flags = [0; 8192];
638                 for t in types {
639                         flags[*t as usize >> 3] |= 1 << (7 - (*t as usize % 8));
640                 }
641                 let res = Self(flags);
642                 for t in types {
643                         debug_assert!(res.contains_type(*t));
644                 }
645                 res
646         }
647         /// Checks if the given type (from [`Record::ty`]) is set, indicating a record of this type
648         /// exists.
649         pub fn contains_type(&self, ty: u16) -> bool {
650                 let f = self.0[(ty >> 3) as usize];
651                 // DNSSEC's bit fields are in wire order, so the high bit is type 0, etc.
652                 f & (1 << (7 - (ty % 8))) != 0
653         }
654         fn write_json(&self, s: &mut String) {
655                 *s += "[";
656                 let mut have_written = false;
657                 for (idx, mask) in self.0.iter().enumerate() {
658                         if *mask == 0 { continue; }
659                         for b in 0..8 {
660                                 if *mask & (1 << b) != 0 {
661                                         if have_written {
662                                                 *s += ",";
663                                         }
664                                         have_written = true;
665                                         let ty = ((idx as u16) << 3) | (7 - b);
666                                         match RR::ty_to_rr_name(ty) {
667                                                 Some(name) => write!(s, "\"{}\"", name).expect("Writes to a string shouldn't fail"),
668                                                 _ => write!(s, "{}", ty).expect("Writes to a string shouldn't fail"),
669                                         }
670                                 }
671                         }
672                 }
673                 *s += "]";
674         }
675 }
676
677 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
678 /// A Next Secure Record resource record. This indicates a range of possible names for which there
679 /// is no such record.
680 pub struct NSec {
681         /// The name this record is at.
682         pub name: Name,
683         /// The next name which contains a record. There are no names between `name` and
684         /// [`Self::next_name`].
685         pub next_name: Name,
686         /// The set of record types which exist at `name`. Any other record types do not exist at
687         /// `name`.
688         pub types: NSecTypeMask,
689 }
690 impl StaticRecord for NSec {
691         const TYPE: u16 = 47;
692         fn name(&self) -> &Name { &self.name }
693         fn json(&self) -> String {
694                 let mut out = String::with_capacity(256 + self.next_name.len());
695                 write!(&mut out,
696                         "{{\"type\":\"nsec\",\"name\":\"{}\",\"next_name\":\"{}\",\"types\":",
697                         self.name.0, self.next_name.0,
698                 ).expect("Write to a String shouldn't fail");
699                 self.types.write_json(&mut out);
700                 out += "}";
701                 out
702         }
703         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
704                 let res = NSec {
705                         name, next_name: read_wire_packet_name(&mut data, wire_packet)?,
706                         types: NSecTypeMask(read_nsec_types_bitmap(&mut data)?),
707                 };
708                 debug_assert!(data.is_empty());
709                 Ok(res)
710         }
711         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
712                 let len = name_len(&self.next_name) + nsec_types_bitmap_len(&self.types.0);
713                 out.extend_from_slice(&len.to_be_bytes());
714                 write_name(out, &self.next_name);
715                 write_nsec_types_bitmap(out, &self.types.0);
716         }
717 }
718
719 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
720 /// A Next Secure Record resource record. This indicates a range of possible names for which there
721 /// is no such record.
722 pub struct NSec3 {
723         /// The name this record is at.
724         pub name: Name,
725         /// The hash algorithm used to hash the `name` and [`Self::next_name_hash`]. Currently only 1
726         /// (SHA-1) is defined.
727         pub hash_algo: u8,
728         /// Flags for this record. Currently only bit 0 (the "opt-out" bit) is defined.
729         pub flags: u8,
730         /// The number of hash iterations required.
731         ///
732         /// As of RFC 9276 this MUST be set to 0, but sadly is often still set higher in the wild. A
733         /// hard cap is applied in validation.
734         pub hash_iterations: u16,
735         /// The salt included in the hash.
736         ///
737         /// As of RFC 9276 this SHOULD be empty, but often isn't in the wild.
738         pub salt: Vec<u8>,
739         /// The hash of the next name which contains a record. There are no records who's name's hash
740         /// lies between `name` and [`Self::next_name_hash`].
741         pub next_name_hash: Vec<u8>,
742         /// The set of record types which exist at `name`. Any other record types do not exist at
743         /// `name`.
744         pub types: NSecTypeMask,
745 }
746 impl StaticRecord for NSec3 {
747         const TYPE: u16 = 50;
748         fn name(&self) -> &Name { &self.name }
749         fn json(&self) -> String {
750                 let mut out = String::with_capacity(256);
751                 write!(&mut out,
752                         "{{\"type\":\"nsec3\",\"name\":\"{}\",\"hash_algo\":{},\"flags\":{},\"hash_iterations\":{},\"salt\":{:?},\"next_name_hash\":{:?},\"types\":",
753                         self.name.0, self.hash_algo, self.flags, self.hash_iterations, &self.salt[..], &self.next_name_hash[..]
754                 ).expect("Write to a String shouldn't fail");
755                 self.types.write_json(&mut out);
756                 out += "}";
757                 out
758         }
759         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
760                 let res = NSec3 {
761                         name, hash_algo: read_u8(&mut data)?, flags: read_u8(&mut data)?,
762                         hash_iterations: read_u16(&mut data)?, salt: read_u8_len_prefixed_bytes(&mut data)?,
763                         next_name_hash: read_u8_len_prefixed_bytes(&mut data)?,
764                         types: NSecTypeMask(read_nsec_types_bitmap(&mut data)?),
765                 };
766                 debug_assert!(data.is_empty());
767                 Ok(res)
768         }
769         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
770                 let len = 4 + 2 + self.salt.len() as u16 + self.next_name_hash.len() as u16 +
771                         nsec_types_bitmap_len(&self.types.0);
772                 out.extend_from_slice(&len.to_be_bytes());
773                 out.extend_from_slice(&self.hash_algo.to_be_bytes());
774                 out.extend_from_slice(&self.flags.to_be_bytes());
775                 out.extend_from_slice(&self.hash_iterations.to_be_bytes());
776                 out.extend_from_slice(&(self.salt.len() as u8).to_be_bytes());
777                 out.extend_from_slice(&self.salt);
778                 out.extend_from_slice(&(self.next_name_hash.len() as u8).to_be_bytes());
779                 out.extend_from_slice(&self.next_name_hash);
780                 write_nsec_types_bitmap(out, &self.types.0);
781         }
782 }
783
784 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
785 /// An IPv4 Address resource record
786 pub struct A {
787         /// The name this record is at.
788         pub name: Name,
789         /// The bytes of the IPv4 address.
790         pub address: [u8; 4],
791 }
792 /// The wire type for A records
793 pub const A_TYPE: u16 = 1;
794 impl StaticRecord for A {
795         const TYPE: u16 = A_TYPE;
796         fn name(&self) -> &Name { &self.name }
797         fn json(&self) -> String {
798                 format!("{{\"type\":\"a\",\"name\":\"{}\",\"address\":{:?}}}", self.name.0, self.address)
799         }
800         fn read_from_data(name: Name, data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
801                 if data.len() != 4 { return Err(()); }
802                 let mut address = [0; 4];
803                 address.copy_from_slice(&data);
804                 Ok(A { name, address })
805         }
806         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
807                 out.extend_from_slice(&4u16.to_be_bytes());
808                 out.extend_from_slice(&self.address);
809         }
810 }
811
812 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
813 /// An IPv6 Address resource record
814 pub struct AAAA {
815         /// The name this record is at.
816         pub name: Name,
817         /// The bytes of the IPv6 address.
818         pub address: [u8; 16],
819 }
820 /// The wire type for AAAA records
821 pub const AAAA_TYPE: u16 = 28;
822 impl StaticRecord for AAAA {
823         const TYPE: u16 = AAAA_TYPE;
824         fn name(&self) -> &Name { &self.name }
825         fn json(&self) -> String {
826                 format!("{{\"type\":\"aaaa\",\"name\":\"{}\",\"address\":{:?}}}", self.name.0, self.address)
827         }
828         fn read_from_data(name: Name, data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
829                 if data.len() != 16 { return Err(()); }
830                 let mut address = [0; 16];
831                 address.copy_from_slice(&data);
832                 Ok(AAAA { name, address })
833         }
834         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
835                 out.extend_from_slice(&16u16.to_be_bytes());
836                 out.extend_from_slice(&self.address);
837         }
838 }
839
840 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
841 /// A Name Server resource record, which indicates the server responsible for handling queries for
842 /// a zone.
843 pub struct NS {
844         /// The name this record is at.
845         ///
846         /// This is also the zone which the server at [`Self::name_server`] is responsible for handling
847         /// queries for.
848         pub name: Name,
849         /// The name of the server which is responsible for handling queries for the [`self.name`]
850         /// zone.
851         pub name_server: Name,
852 }
853 impl StaticRecord for NS {
854         const TYPE: u16 = 2;
855         fn name(&self) -> &Name { &self.name }
856         fn json(&self) -> String {
857                 format!("{{\"type\":\"ns\",\"name\":\"{}\",\"ns\":\"{}\"}}", self.name.0, self.name_server.0)
858         }
859         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
860                 let res = NS { name, name_server: read_wire_packet_name(&mut data, wire_packet)? };
861                 debug_assert!(data.is_empty());
862                 Ok(res)
863         }
864         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
865                 out.extend_from_slice(&name_len(&self.name_server).to_be_bytes());
866                 write_name(out, &self.name_server);
867         }
868 }