Correct TXT sort order on unlikely edge cases
[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::{self, 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(|| {
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; }
183                                 }
184                                 Ordering::Equal
185                         }))
186         }
187 }
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]);
197                         data = &data[len..];
198                 }
199                 Ok(Txt { name, data: parsed_data })
200         }
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());
204
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)]);
213                         }
214                 }
215         }
216 }
217
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.
221 ///
222 /// See <https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities#TLSA_RR> for more
223 /// info.
224 pub struct TLSA {
225         /// The name this record is at.
226         pub name: Name,
227         /// The type of constraint on the TLS certificate(s) used which should be enforced by this
228         /// record.
229         pub cert_usage: u8,
230         /// Whether to match on the full certificate, or only the public key.
231         pub selector: u8,
232         /// The type of data included which is used to match the TLS certificate(s).
233         pub data_ty: u8,
234         /// The certificate data or hash of the certificate data itself.
235         pub data: Vec<u8>,
236 }
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, ()> {
241                 Ok(TLSA {
242                         name, cert_usage: read_u8(&mut data)?, selector: read_u8(&mut data)?,
243                         data_ty: read_u8(&mut data)?, data: data.to_vec(),
244                 })
245         }
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);
251         }
252 }
253
254 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
255 /// A Canonical Name resource record, referring all queries for this name to another name.
256 pub struct CName {
257         /// The name this record is at.
258         pub name: Name,
259         /// The canonical name.
260         ///
261         /// A resolver should use this name when looking up any further records for [`Self::name`].
262         pub canonical_name: Name,
263 }
264 impl StaticRecord for CName {
265         const TYPE: u16 = 5;
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)? })
269         }
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);
274         }
275 }
276
277 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
278 /// A public key resource record which can be used to validate [`RRSig`]s.
279 pub struct DnsKey {
280         /// The name this record is at.
281         pub name: Name,
282         /// Flags which constrain the usage of this public key.
283         pub flags: u16,
284         /// The protocol this key is used for (protocol `3` is DNSSEC). 
285         pub protocol: u8,
286         /// The algorithm which this public key uses to sign data.
287         pub alg: u8,
288         /// The public key itself.
289         pub pubkey: Vec<u8>,
290 }
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, ()> {
295                 Ok(DnsKey {
296                         name, flags: read_u16(&mut data)?, protocol: read_u8(&mut data)?,
297                         alg: read_u8(&mut data)?, pubkey: data.to_vec(),
298                 })
299         }
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);
307         }
308 }
309 impl DnsKey {
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() {
316                         if idx % 2 == 0 {
317                                 res += u32::from(*b) << 8;
318                         } else {
319                                 res += u32::from(*b);
320                         }
321                 }
322                 res += (res >> 16) & 0xffff;
323                 (res & 0xffff) as u16
324         }
325 }
326
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`].
330 pub struct DS {
331         /// The name this record is at.
332         ///
333         /// This is also the zone that a [`DnsKey`] which matches the [`Self::digest`] can sign for.
334         pub name: Name,
335         /// A short tag which describes the matching [`DnsKey`].
336         ///
337         /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which is referred to by this
338         /// [`DS`].
339         pub key_tag: u16,
340         /// The algorithm which the [`DnsKey`] referred to by this [`DS`] uses.
341         ///
342         /// This matches the [`DnsKey::alg`] field in the referred-to [`DnsKey`].
343         pub alg: u8,
344         /// The type of digest used to hash the referred-to [`DnsKey`].
345         pub digest_type: u8,
346         /// The digest itself.
347         pub digest: Vec<u8>,
348 }
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, ()> {
353                 Ok(DS {
354                         name, key_tag: read_u16(&mut data)?, alg: read_u8(&mut data)?,
355                         digest_type: read_u8(&mut data)?, digest: data.to_vec(),
356                 })
357         }
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);
365         }
366 }
367
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.
371 pub struct RRSig {
372         /// The name this record is at.
373         ///
374         /// This is also the name of any records which this signature is covering (ignoring wildcards).
375         pub name: Name,
376         /// The resource record type which this [`RRSig`] is signing.
377         ///
378         /// All resources records of this type at the same name as [`Self::name`] must be signed by
379         /// this [`RRSig`].
380         pub ty: u16,
381         /// The algorithm which is being used to sign.
382         ///
383         /// This must match the [`DnsKey::alg`] field in the [`DnsKey`] being used to sign.
384         pub alg: u8,
385         /// The number of labels in the name of the records that this signature is signing.
386         ///
387         /// If this is less than the number of labels in [`Self::name`], this signature is covering a
388         /// wildcard entry.
389         pub labels: u8,
390         /// The TTL of the records which this [`RRSig`] is signing.
391         pub orig_ttl: u32,
392         /// The expiration (as a UNIX timestamp) of this signature.
393         pub expiration: u32,
394         /// The time (as a UNIX timestamp) at which this signature becomes valid.
395         pub inception: u32,
396         /// A short tag which describes the matching [`DnsKey`].
397         ///
398         /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which created this signature.
399         pub key_tag: u16,
400         /// The [`DnsKey::name`] in the [`DnsKey`] which created this signature.
401         ///
402         /// This must be a parent of the [`Self::name`].
403         pub key_name: Name,
404         /// The signature itself.
405         pub signature: Vec<u8>,
406 }
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, ()> {
411                 Ok(RRSig {
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(),
418                 })
419         }
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);
432         }
433 }
434
435 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
436 /// An IPv4 Address resource record
437 pub struct A {
438         /// The name this record is at.
439         pub name: Name,
440         /// The bytes of the IPv4 address.
441         pub address: [u8; 4],
442 }
443 impl StaticRecord for A {
444         const TYPE: u16 = 1;
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 })
451         }
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);
455         }
456 }
457
458 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
459 /// An IPv6 Address resource record
460 pub struct AAAA {
461         /// The name this record is at.
462         pub name: Name,
463         /// The bytes of the IPv6 address.
464         pub address: [u8; 16],
465 }
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 })
474         }
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);
478         }
479 }
480
481 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
482 /// A Name Server resource record, which indicates the server responsible for handling queries for
483 /// a zone.
484 pub struct NS {
485         /// The name this record is at.
486         ///
487         /// This is also the zone which the server at [`Self::name_server`] is responsible for handling
488         /// queries for.
489         pub name: Name,
490         /// The name of the server which is responsible for handling queries for the [`Self::name`]
491         /// zone.
492         pub name_server: Name,
493 }
494 impl StaticRecord for NS {
495         const TYPE: u16 = 2;
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)? })
499         }
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);
503         }
504 }