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