14826e3d1e00c53c76b691e4c06ef9ed762dd791
[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
10 use core::cmp::Ordering;
11
12 use crate::ser::*;
13
14 /// A valid domain name.
15 ///
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);
20 impl Name {
21         /// Gets the underlying human-readable domain name
22         pub fn as_str(&self) -> &str { &self.0 }
23 }
24 impl core::ops::Deref for Name {
25         type Target = str;
26         fn deref(&self) -> &str { &self.0 }
27 }
28 impl TryFrom<String> for Name {
29         type Error = ();
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(()); }
37                 }
38
39                 Ok(Name(s))
40         }
41 }
42 impl TryFrom<&str> for Name {
43         type Error = ();
44         fn try_from(s: &str) -> Result<Name, ()> {
45                 Self::try_from(s.to_owned())
46         }
47 }
48
49 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
50 /// A supported Resource Record
51 ///
52 /// Note that we only currently support a handful of RR types as needed to generate and validate
53 /// TXT or TLSA record proofs.
54 pub enum RR {
55         /// An IPv4 resource record
56         A(A),
57         /// An IPv6 resource record
58         AAAA(AAAA),
59         /// A name server resource record
60         NS(NS),
61         /// A text resource record
62         Txt(Txt),
63         /// A TLS Certificate Association resource record
64         TLSA(TLSA),
65         /// A Canonical Name record
66         CName(CName),
67         /// A DNS (Public) Key resource record
68         DnsKey(DnsKey),
69         /// A Delegated Signer resource record
70         DS(DS),
71         /// A Resource Record Signature record
72         RRSig(RRSig),
73 }
74 impl RR {
75         /// Gets the name this record refers to.
76         pub fn name(&self) -> &Name {
77                 match self {
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,
87                 }
88         }
89         fn ty(&self) -> u16 {
90                 match self {
91                         RR::A(_) => A::TYPE,
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,
100                 }
101         }
102         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
103                 match self {
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),
113                 }
114         }
115 }
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) } }
125
126 pub(crate) trait StaticRecord : Ord + Sized {
127         // http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4
128         const TYPE: u16;
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, ()>;
132 }
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.
136         ///
137         /// Current assignments can be found at
138         /// <http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4>
139         fn ty(&self) -> u16;
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>);
144 }
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)
150         }
151 }
152 impl Record for RR {
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)
157         }
158 }
159
160 #[derive(Debug, Clone, PartialEq, Eq, Ord)]
161 /// A text resource record, containing arbitrary text data
162 pub struct Txt {
163         /// The name this record is at.
164         pub name: Name,
165         /// The text record itself.
166         ///
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.
169         pub data: Vec<u8>,
170 }
171 impl PartialOrd for Txt {
172         fn partial_cmp(&self, o: &Txt) -> Option<Ordering> {
173                 Some(self.name.cmp(&o.name)
174                         .then_with(|| self.data.len().cmp(&o.data.len()))
175                         .then_with(|| self.data.cmp(&o.data)))
176         }
177 }
178 impl StaticRecord for Txt {
179         const TYPE: u16 = 16;
180         fn name(&self) -> &Name { &self.name }
181         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
182                 let mut parsed_data = Vec::with_capacity(data.len() - 1);
183                 while !data.is_empty() {
184                         let len = read_u8(&mut data)? as usize;
185                         if data.len() < len { return Err(()); }
186                         parsed_data.extend_from_slice(&data[..len]);
187                         data = &data[len..];
188                 }
189                 Ok(Txt { name, data: parsed_data })
190         }
191         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
192                 let len = (self.data.len() + (self.data.len() + 254) / 255) as u16;
193                 out.extend_from_slice(&len.to_be_bytes());
194
195                 let mut data_write = &self.data[..];
196                 out.extend_from_slice(&[data_write.len().try_into().unwrap_or(255)]);
197                 while !data_write.is_empty() {
198                         let split_pos = core::cmp::min(255, data_write.len());
199                         out.extend_from_slice(&data_write[..split_pos]);
200                         data_write = &data_write[split_pos..];
201                         if !data_write.is_empty() {
202                                 out.extend_from_slice(&[data_write.len().try_into().unwrap_or(255)]);
203                         }
204                 }
205         }
206 }
207
208 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
209 /// A TLS Certificate Association resource record containing information about the TLS certificate
210 /// which should be expected when communicating with the host at the given name.
211 ///
212 /// See <https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities#TLSA_RR> for more
213 /// info.
214 pub struct TLSA {
215         /// The name this record is at.
216         pub name: Name,
217         /// The type of constraint on the TLS certificate(s) used which should be enforced by this
218         /// record.
219         pub cert_usage: u8,
220         /// Whether to match on the full certificate, or only the public key.
221         pub selector: u8,
222         /// The type of data included which is used to match the TLS certificate(s).
223         pub data_ty: u8,
224         /// The certificate data or hash of the certificate data itself.
225         pub data: Vec<u8>,
226 }
227 impl StaticRecord for TLSA {
228         const TYPE: u16 = 52;
229         fn name(&self) -> &Name { &self.name }
230         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
231                 Ok(TLSA {
232                         name, cert_usage: read_u8(&mut data)?, selector: read_u8(&mut data)?,
233                         data_ty: read_u8(&mut data)?, data: data.to_vec(),
234                 })
235         }
236         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
237                 let len = 3 + self.data.len();
238                 out.extend_from_slice(&(len as u16).to_be_bytes());
239                 out.extend_from_slice(&[self.cert_usage, self.selector, self.data_ty]);
240                 out.extend_from_slice(&self.data);
241         }
242 }
243
244 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
245 /// A Canonical Name resource record, referring all queries for this name to another name.
246 pub struct CName {
247         /// The name this record is at.
248         pub name: Name,
249         /// The canonical name.
250         ///
251         /// A resolver should use this name when looking up any further records for [`Self::name`].
252         pub canonical_name: Name,
253 }
254 impl StaticRecord for CName {
255         const TYPE: u16 = 5;
256         fn name(&self) -> &Name { &self.name }
257         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
258                 Ok(CName { name, canonical_name: read_wire_packet_name(&mut data, wire_packet)? })
259         }
260         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
261                 let len: u16 = name_len(&self.canonical_name);
262                 out.extend_from_slice(&len.to_be_bytes());
263                 write_name(out, &self.canonical_name);
264         }
265 }
266
267 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
268 /// A public key resource record which can be used to validate [`RRSig`]s.
269 pub struct DnsKey {
270         /// The name this record is at.
271         pub name: Name,
272         /// Flags which constrain the usage of this public key.
273         pub flags: u16,
274         /// The protocol this key is used for (protocol `3` is DNSSEC). 
275         pub protocol: u8,
276         /// The algorithm which this public key uses to sign data.
277         pub alg: u8,
278         /// The public key itself.
279         pub pubkey: Vec<u8>,
280 }
281 impl StaticRecord for DnsKey {
282         const TYPE: u16 = 48;
283         fn name(&self) -> &Name { &self.name }
284         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
285                 Ok(DnsKey {
286                         name, flags: read_u16(&mut data)?, protocol: read_u8(&mut data)?,
287                         alg: read_u8(&mut data)?, pubkey: data.to_vec(),
288                 })
289         }
290         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
291                 let len = 2 + 1 + 1 + self.pubkey.len();
292                 out.extend_from_slice(&(len as u16).to_be_bytes());
293                 out.extend_from_slice(&self.flags.to_be_bytes());
294                 out.extend_from_slice(&self.protocol.to_be_bytes());
295                 out.extend_from_slice(&self.alg.to_be_bytes());
296                 out.extend_from_slice(&self.pubkey);
297         }
298 }
299 impl DnsKey {
300         /// A short (non-cryptographic) digest which can be used to refer to this [`DnsKey`].
301         pub fn key_tag(&self) -> u16 {
302                 let mut res = u32::from(self.flags);
303                 res += u32::from(self.protocol) << 8;
304                 res += u32::from(self.alg);
305                 for (idx, b) in self.pubkey.iter().enumerate() {
306                         if idx % 2 == 0 {
307                                 res += u32::from(*b) << 8;
308                         } else {
309                                 res += u32::from(*b);
310                         }
311                 }
312                 res += (res >> 16) & 0xffff;
313                 (res & 0xffff) as u16
314         }
315 }
316
317 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
318 /// A Delegation Signer resource record which indicates that some alternative [`DnsKey`] can sign
319 /// for records in the zone which matches [`DS::name`].
320 pub struct DS {
321         /// The name this record is at.
322         ///
323         /// This is also the zone that a [`DnsKey`] which matches the [`Self::digest`] can sign for.
324         pub name: Name,
325         /// A short tag which describes the matching [`DnsKey`].
326         ///
327         /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which is referred to by this
328         /// [`DS`].
329         pub key_tag: u16,
330         /// The algorithm which the [`DnsKey`] referred to by this [`DS`] uses.
331         ///
332         /// This matches the [`DnsKey::alg`] field in the referred-to [`DnsKey`].
333         pub alg: u8,
334         /// The type of digest used to hash the referred-to [`DnsKey`].
335         pub digest_type: u8,
336         /// The digest itself.
337         pub digest: Vec<u8>,
338 }
339 impl StaticRecord for DS {
340         const TYPE: u16 = 43;
341         fn name(&self) -> &Name { &self.name }
342         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
343                 Ok(DS {
344                         name, key_tag: read_u16(&mut data)?, alg: read_u8(&mut data)?,
345                         digest_type: read_u8(&mut data)?, digest: data.to_vec(),
346                 })
347         }
348         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
349                 let len = 2 + 1 + 1 + self.digest.len();
350                 out.extend_from_slice(&(len as u16).to_be_bytes());
351                 out.extend_from_slice(&self.key_tag.to_be_bytes());
352                 out.extend_from_slice(&self.alg.to_be_bytes());
353                 out.extend_from_slice(&self.digest_type.to_be_bytes());
354                 out.extend_from_slice(&self.digest);
355         }
356 }
357
358 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
359 /// A Resource Record (set) Signature resource record. This contains a signature over all the
360 /// resources records of the given type at the given name.
361 pub struct RRSig {
362         /// The name this record is at.
363         ///
364         /// This is also the name of any records which this signature is covering (ignoring wildcards).
365         pub name: Name,
366         /// The resource record type which this [`RRSig`] is signing.
367         ///
368         /// All resources records of this type at the same name as [`Self::name`] must be signed by
369         /// this [`RRSig`].
370         pub ty: u16,
371         /// The algorithm which is being used to sign.
372         ///
373         /// This must match the [`DnsKey::alg`] field in the [`DnsKey`] being used to sign.
374         pub alg: u8,
375         /// The number of labels in the name of the records that this signature is signing.
376         ///
377         /// If this is less than the number of labels in [`Self::name`], this signature is covering a
378         /// wildcard entry.
379         pub labels: u8,
380         /// The TTL of the records which this [`RRSig`] is signing.
381         pub orig_ttl: u32,
382         /// The expiration (as a UNIX timestamp) of this signature.
383         pub expiration: u32,
384         /// The time (as a UNIX timestamp) at which this signature becomes valid.
385         pub inception: u32,
386         /// A short tag which describes the matching [`DnsKey`].
387         ///
388         /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which created this signature.
389         pub key_tag: u16,
390         /// The [`DnsKey::name`] in the [`DnsKey`] which created this signature.
391         ///
392         /// This must be a parent of the [`Self::name`].
393         pub key_name: Name,
394         /// The signature itself.
395         pub signature: Vec<u8>,
396 }
397 impl StaticRecord for RRSig {
398         const TYPE: u16 = 46;
399         fn name(&self) -> &Name { &self.name }
400         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
401                 Ok(RRSig {
402                         name, ty: read_u16(&mut data)?, alg: read_u8(&mut data)?,
403                         labels: read_u8(&mut data)?, orig_ttl: read_u32(&mut data)?,
404                         expiration: read_u32(&mut data)?, inception: read_u32(&mut data)?,
405                         key_tag: read_u16(&mut data)?,
406                         key_name: read_wire_packet_name(&mut data, wire_packet)?,
407                         signature: data.to_vec(),
408                 })
409         }
410         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
411                 let len = 2 + 1 + 1 + 4*3 + 2 + name_len(&self.key_name) + self.signature.len() as u16;
412                 out.extend_from_slice(&len.to_be_bytes());
413                 out.extend_from_slice(&self.ty.to_be_bytes());
414                 out.extend_from_slice(&self.alg.to_be_bytes());
415                 out.extend_from_slice(&self.labels.to_be_bytes());
416                 out.extend_from_slice(&self.orig_ttl.to_be_bytes());
417                 out.extend_from_slice(&self.expiration.to_be_bytes());
418                 out.extend_from_slice(&self.inception.to_be_bytes());
419                 out.extend_from_slice(&self.key_tag.to_be_bytes());
420                 write_name(out, &self.key_name);
421                 out.extend_from_slice(&self.signature);
422         }
423 }
424
425 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
426 /// An IPv4 Address resource record
427 pub struct A {
428         /// The name this record is at.
429         pub name: Name,
430         /// The bytes of the IPv4 address.
431         pub address: [u8; 4],
432 }
433 impl StaticRecord for A {
434         const TYPE: u16 = 1;
435         fn name(&self) -> &Name { &self.name }
436         fn read_from_data(name: Name, data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
437                 if data.len() != 4 { return Err(()); }
438                 let mut address = [0; 4];
439                 address.copy_from_slice(&data);
440                 Ok(A { name, address })
441         }
442         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
443                 out.extend_from_slice(&4u16.to_be_bytes());
444                 out.extend_from_slice(&self.address);
445         }
446 }
447
448 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
449 /// An IPv6 Address resource record
450 pub struct AAAA {
451         /// The name this record is at.
452         pub name: Name,
453         /// The bytes of the IPv6 address.
454         pub address: [u8; 16],
455 }
456 impl StaticRecord for AAAA {
457         const TYPE: u16 = 28;
458         fn name(&self) -> &Name { &self.name }
459         fn read_from_data(name: Name, data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
460                 if data.len() != 16 { return Err(()); }
461                 let mut address = [0; 16];
462                 address.copy_from_slice(&data);
463                 Ok(AAAA { name, address })
464         }
465         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
466                 out.extend_from_slice(&16u16.to_be_bytes());
467                 out.extend_from_slice(&self.address);
468         }
469 }
470
471 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
472 /// A Name Server resource record, which indicates the server responsible for handling queries for
473 /// a zone.
474 pub struct NS {
475         /// The name this record is at.
476         ///
477         /// This is also the zone which the server at [`Self::name_server`] is responsible for handling
478         /// queries for.
479         pub name: Name,
480         /// The name of the server which is responsible for handling queries for the [`Self::name`]
481         /// zone.
482         pub name_server: Name,
483 }
484 impl StaticRecord for NS {
485         const TYPE: u16 = 2;
486         fn name(&self) -> &Name { &self.name }
487         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
488                 Ok(NS { name, name_server: read_wire_packet_name(&mut data, wire_packet)? })
489         }
490         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
491                 out.extend_from_slice(&name_len(&self.name_server).to_be_bytes());
492                 write_name(out, &self.name_server);
493         }
494 }