Skip to main content

ms_dnsp/
lib.rs

1//! Parser and builder for the **`dnsRecord`** blob — how an Active-Directory-integrated DNS
2//! zone stores each resource record (MS-DNSP §2.3.2.2, `DNS_RPC_RECORD`).
3//!
4//! A `dnsNode` object under `DC=<zone>,CN=MicrosoftDNS,…` carries one multi-valued
5//! `dnsRecord` attribute; every value is one of these blobs: a 24-byte header followed by
6//! type-specific data. Nothing here talks to a network or to LDAP — it is bytes in, records
7//! out, and back again.
8//!
9//! ```
10//! use ms_dnsp::{DnsRecord, RecordData};
11//! use std::net::Ipv4Addr;
12//!
13//! let rec = DnsRecord::new(RecordData::A("10.0.0.1".parse().unwrap())).with_ttl(600);
14//! let blob = rec.to_bytes();
15//! assert_eq!(DnsRecord::parse(&blob).unwrap(), rec);
16//! ```
17//!
18//! Parsing never panics: every length byte is validated against the buffer first.
19
20pub mod name;
21
22use std::net::{Ipv4Addr, Ipv6Addr};
23
24use name::{read_count_name, read_rpc_name, write_count_name, write_rpc_name};
25
26/// Size of the fixed `DNS_RPC_RECORD` header that precedes the record data.
27pub const HEADER_LEN: usize = 24;
28/// The record-structure version Windows writes.
29pub const VERSION: u8 = 5;
30
31#[derive(Debug, thiserror::Error, PartialEq, Eq)]
32pub enum DnsError {
33    #[error("truncated at offset {0}")]
34    Truncated(usize),
35    #[error("dnsRecord claims {claimed} data bytes, {actual} present")]
36    BadDataLength { claimed: usize, actual: usize },
37    #[error("malformed DNS name at offset {0}")]
38    BadName(usize),
39    #[error("record data too short for type {ty}: {len} bytes")]
40    ShortData { ty: u16, len: usize },
41}
42
43pub type Result<T> = std::result::Result<T, DnsError>;
44
45/// `DNS_RECORD_TYPE` values this crate models explicitly.
46pub mod ty {
47    pub const ZERO: u16 = 0x0000;
48    pub const A: u16 = 0x0001;
49    pub const NS: u16 = 0x0002;
50    pub const CNAME: u16 = 0x0005;
51    pub const SOA: u16 = 0x0006;
52    pub const PTR: u16 = 0x000C;
53    pub const MX: u16 = 0x000F;
54    pub const TXT: u16 = 0x0010;
55    pub const AAAA: u16 = 0x001C;
56    pub const SRV: u16 = 0x0021;
57}
58
59/// Where the record came from — DNS uses this to decide which copy wins.
60pub mod rank {
61    pub const CACHE_BIT: u8 = 0x01;
62    pub const ROOT_HINT: u8 = 0x08;
63    pub const OUTSIDE_GLUE: u8 = 0x20;
64    pub const CACHE_NA_ADDITIONAL: u8 = 0x31;
65    pub const CACHE_NA_AUTHORITY: u8 = 0x41;
66    pub const CACHE_A_ADDITIONAL: u8 = 0x51;
67    pub const CACHE_NA_ANSWER: u8 = 0x61;
68    pub const CACHE_A_AUTHORITY: u8 = 0x71;
69    pub const CACHE_A_ANSWER: u8 = 0xC1;
70    pub const GLUE: u8 = 0x80;
71    pub const NS_GLUE: u8 = 0x82;
72    /// The record is authoritative zone data — what you see on a DC's own zone.
73    pub const ZONE: u8 = 0xF0;
74}
75
76/// The type-specific half of a record.
77#[derive(Clone, Debug, PartialEq, Eq)]
78pub enum RecordData {
79    A(Ipv4Addr),
80    Aaaa(Ipv6Addr),
81    Ns(String),
82    Cname(String),
83    Ptr(String),
84    Soa {
85        serial: u32,
86        refresh: u32,
87        retry: u32,
88        expire: u32,
89        minimum_ttl: u32,
90        primary_server: String,
91        responsible_party: String,
92    },
93    Mx {
94        preference: u16,
95        exchange: String,
96    },
97    Srv {
98        priority: u16,
99        weight: u16,
100        port: u16,
101        target: String,
102    },
103    Txt(Vec<String>),
104    /// `DNS_TYPE_ZERO` — a tombstone. The payload is the entombed time as a FILETIME.
105    Tombstone(u64),
106    /// Any other record type, kept verbatim so a round-trip is lossless.
107    Unknown {
108        ty: u16,
109        bytes: Vec<u8>,
110    },
111}
112
113impl RecordData {
114    /// The `DNS_RECORD_TYPE` code this data belongs to.
115    pub fn record_type(&self) -> u16 {
116        match self {
117            RecordData::A(_) => ty::A,
118            RecordData::Aaaa(_) => ty::AAAA,
119            RecordData::Ns(_) => ty::NS,
120            RecordData::Cname(_) => ty::CNAME,
121            RecordData::Ptr(_) => ty::PTR,
122            RecordData::Soa { .. } => ty::SOA,
123            RecordData::Mx { .. } => ty::MX,
124            RecordData::Srv { .. } => ty::SRV,
125            RecordData::Txt(_) => ty::TXT,
126            RecordData::Tombstone(_) => ty::ZERO,
127            RecordData::Unknown { ty, .. } => *ty,
128        }
129    }
130
131    /// Encode just the data half (what `wDataLength` counts).
132    pub fn to_bytes(&self) -> Vec<u8> {
133        let mut out = Vec::new();
134        match self {
135            RecordData::A(ip) => out.extend_from_slice(&ip.octets()),
136            RecordData::Aaaa(ip) => out.extend_from_slice(&ip.octets()),
137            RecordData::Ns(n) | RecordData::Cname(n) | RecordData::Ptr(n) => {
138                write_count_name(&mut out, n)
139            }
140            RecordData::Soa {
141                serial,
142                refresh,
143                retry,
144                expire,
145                minimum_ttl,
146                primary_server,
147                responsible_party,
148            } => {
149                for v in [serial, refresh, retry, expire, minimum_ttl] {
150                    out.extend_from_slice(&v.to_be_bytes());
151                }
152                write_count_name(&mut out, primary_server);
153                write_count_name(&mut out, responsible_party);
154            }
155            RecordData::Mx {
156                preference,
157                exchange,
158            } => {
159                out.extend_from_slice(&preference.to_be_bytes());
160                write_count_name(&mut out, exchange);
161            }
162            RecordData::Srv {
163                priority,
164                weight,
165                port,
166                target,
167            } => {
168                out.extend_from_slice(&priority.to_be_bytes());
169                out.extend_from_slice(&weight.to_be_bytes());
170                out.extend_from_slice(&port.to_be_bytes());
171                write_count_name(&mut out, target);
172            }
173            RecordData::Txt(strings) => {
174                for s in strings {
175                    write_rpc_name(&mut out, s);
176                }
177            }
178            RecordData::Tombstone(t) => out.extend_from_slice(&t.to_le_bytes()),
179            RecordData::Unknown { bytes, .. } => out.extend_from_slice(bytes),
180        }
181        out
182    }
183
184    fn parse(ty: u16, b: &[u8]) -> Result<RecordData> {
185        let short = || DnsError::ShortData { ty, len: b.len() };
186        Ok(match ty {
187            ty::A => {
188                let o: [u8; 4] = b.get(..4).ok_or_else(short)?.try_into().unwrap();
189                RecordData::A(Ipv4Addr::from(o))
190            }
191            ty::AAAA => {
192                let o: [u8; 16] = b.get(..16).ok_or_else(short)?.try_into().unwrap();
193                RecordData::Aaaa(Ipv6Addr::from(o))
194            }
195            ty::NS => RecordData::Ns(read_count_name(b, &mut 0)?),
196            ty::CNAME => RecordData::Cname(read_count_name(b, &mut 0)?),
197            ty::PTR => RecordData::Ptr(read_count_name(b, &mut 0)?),
198            ty::SOA => {
199                if b.len() < 20 {
200                    return Err(short());
201                }
202                let be = |i: usize| u32::from_be_bytes(b[i..i + 4].try_into().unwrap());
203                let mut cur = 20;
204                let primary_server = read_count_name(b, &mut cur)?;
205                let responsible_party = read_count_name(b, &mut cur)?;
206                RecordData::Soa {
207                    serial: be(0),
208                    refresh: be(4),
209                    retry: be(8),
210                    expire: be(12),
211                    minimum_ttl: be(16),
212                    primary_server,
213                    responsible_party,
214                }
215            }
216            ty::MX => {
217                if b.len() < 2 {
218                    return Err(short());
219                }
220                let mut cur = 2;
221                RecordData::Mx {
222                    preference: u16::from_be_bytes(b[..2].try_into().unwrap()),
223                    exchange: read_count_name(b, &mut cur)?,
224                }
225            }
226            ty::SRV => {
227                if b.len() < 6 {
228                    return Err(short());
229                }
230                let be = |i: usize| u16::from_be_bytes(b[i..i + 2].try_into().unwrap());
231                let mut cur = 6;
232                RecordData::Srv {
233                    priority: be(0),
234                    weight: be(2),
235                    port: be(4),
236                    target: read_count_name(b, &mut cur)?,
237                }
238            }
239            ty::TXT => {
240                let mut cur = 0;
241                let mut strings = Vec::new();
242                while cur < b.len() {
243                    strings.push(read_rpc_name(b, &mut cur)?);
244                }
245                RecordData::Txt(strings)
246            }
247            ty::ZERO => {
248                let o: [u8; 8] = b.get(..8).ok_or_else(short)?.try_into().unwrap();
249                RecordData::Tombstone(u64::from_le_bytes(o))
250            }
251            _ => RecordData::Unknown {
252                ty,
253                bytes: b.to_vec(),
254            },
255        })
256    }
257}
258
259/// One `dnsRecord` attribute value.
260#[derive(Clone, Debug, PartialEq, Eq)]
261pub struct DnsRecord {
262    pub version: u8,
263    /// See [`rank`]; authoritative zone data is [`rank::ZONE`].
264    pub rank: u8,
265    pub flags: u16,
266    /// Zone serial the record was last written with.
267    pub serial: u32,
268    /// TTL in seconds (stored big-endian, unlike every other integer in the header).
269    pub ttl: u32,
270    pub reserved: u32,
271    /// Hours since 1601-01-01 UTC for a dynamic record; `0` means the record is static and
272    /// will never be scavenged. See [`DnsRecord::timestamp_unix`].
273    pub timestamp: u32,
274    pub data: RecordData,
275}
276
277impl DnsRecord {
278    /// A static, zone-authoritative record with a 1-hour TTL.
279    pub fn new(data: RecordData) -> Self {
280        DnsRecord {
281            version: VERSION,
282            rank: rank::ZONE,
283            flags: 0,
284            serial: 1,
285            ttl: 3600,
286            reserved: 0,
287            timestamp: 0,
288            data,
289        }
290    }
291
292    pub fn with_ttl(mut self, ttl: u32) -> Self {
293        self.ttl = ttl;
294        self
295    }
296
297    pub fn with_serial(mut self, serial: u32) -> Self {
298        self.serial = serial;
299        self
300    }
301
302    /// The `DNS_RECORD_TYPE` code.
303    pub fn record_type(&self) -> u16 {
304        self.data.record_type()
305    }
306
307    /// `true` if the record is static — no timestamp, so scavenging leaves it alone.
308    pub fn is_static(&self) -> bool {
309        self.timestamp == 0
310    }
311
312    /// The timestamp as Unix seconds, or `None` for a static record.
313    pub fn timestamp_unix(&self) -> Option<i64> {
314        (self.timestamp != 0).then(|| self.timestamp as i64 * 3600 - 11_644_473_600)
315    }
316
317    /// Parse one `dnsRecord` value.
318    pub fn parse(b: &[u8]) -> Result<DnsRecord> {
319        if b.len() < HEADER_LEN {
320            return Err(DnsError::Truncated(0));
321        }
322        let u16le = |i: usize| u16::from_le_bytes(b[i..i + 2].try_into().unwrap());
323        let u32le = |i: usize| u32::from_le_bytes(b[i..i + 4].try_into().unwrap());
324
325        let data_len = u16le(0) as usize;
326        let ty = u16le(2);
327        let body = b.get(HEADER_LEN..).unwrap_or_default();
328        if body.len() < data_len {
329            return Err(DnsError::BadDataLength {
330                claimed: data_len,
331                actual: body.len(),
332            });
333        }
334
335        Ok(DnsRecord {
336            version: b[4],
337            rank: b[5],
338            flags: u16le(6),
339            serial: u32le(8),
340            // The one big-endian field in the header.
341            ttl: u32::from_be_bytes(b[12..16].try_into().unwrap()),
342            reserved: u32le(16),
343            timestamp: u32le(20),
344            data: RecordData::parse(ty, &body[..data_len])?,
345        })
346    }
347
348    /// Encode back to the on-wire `dnsRecord` value.
349    pub fn to_bytes(&self) -> Vec<u8> {
350        let data = self.data.to_bytes();
351        let mut out = Vec::with_capacity(HEADER_LEN + data.len());
352        out.extend_from_slice(&(data.len() as u16).to_le_bytes());
353        out.extend_from_slice(&self.record_type().to_le_bytes());
354        out.push(self.version);
355        out.push(self.rank);
356        out.extend_from_slice(&self.flags.to_le_bytes());
357        out.extend_from_slice(&self.serial.to_le_bytes());
358        out.extend_from_slice(&self.ttl.to_be_bytes());
359        out.extend_from_slice(&self.reserved.to_le_bytes());
360        out.extend_from_slice(&self.timestamp.to_le_bytes());
361        out.extend_from_slice(&data);
362        out
363    }
364}