ms-dnsp 0.1.0

Pure-Rust parser and builder for the MS-DNSP dnsRecord blob stored in Active-Directory-integrated DNS zones.
Documentation
//! Parser and builder for the **`dnsRecord`** blob — how an Active-Directory-integrated DNS
//! zone stores each resource record (MS-DNSP §2.3.2.2, `DNS_RPC_RECORD`).
//!
//! A `dnsNode` object under `DC=<zone>,CN=MicrosoftDNS,…` carries one multi-valued
//! `dnsRecord` attribute; every value is one of these blobs: a 24-byte header followed by
//! type-specific data. Nothing here talks to a network or to LDAP — it is bytes in, records
//! out, and back again.
//!
//! ```
//! use ms_dnsp::{DnsRecord, RecordData};
//! use std::net::Ipv4Addr;
//!
//! let rec = DnsRecord::new(RecordData::A("10.0.0.1".parse().unwrap())).with_ttl(600);
//! let blob = rec.to_bytes();
//! assert_eq!(DnsRecord::parse(&blob).unwrap(), rec);
//! ```
//!
//! Parsing never panics: every length byte is validated against the buffer first.

pub mod name;

use std::net::{Ipv4Addr, Ipv6Addr};

use name::{read_count_name, read_rpc_name, write_count_name, write_rpc_name};

/// Size of the fixed `DNS_RPC_RECORD` header that precedes the record data.
pub const HEADER_LEN: usize = 24;
/// The record-structure version Windows writes.
pub const VERSION: u8 = 5;

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum DnsError {
    #[error("truncated at offset {0}")]
    Truncated(usize),
    #[error("dnsRecord claims {claimed} data bytes, {actual} present")]
    BadDataLength { claimed: usize, actual: usize },
    #[error("malformed DNS name at offset {0}")]
    BadName(usize),
    #[error("record data too short for type {ty}: {len} bytes")]
    ShortData { ty: u16, len: usize },
}

pub type Result<T> = std::result::Result<T, DnsError>;

/// `DNS_RECORD_TYPE` values this crate models explicitly.
pub mod ty {
    pub const ZERO: u16 = 0x0000;
    pub const A: u16 = 0x0001;
    pub const NS: u16 = 0x0002;
    pub const CNAME: u16 = 0x0005;
    pub const SOA: u16 = 0x0006;
    pub const PTR: u16 = 0x000C;
    pub const MX: u16 = 0x000F;
    pub const TXT: u16 = 0x0010;
    pub const AAAA: u16 = 0x001C;
    pub const SRV: u16 = 0x0021;
}

/// Where the record came from — DNS uses this to decide which copy wins.
pub mod rank {
    pub const CACHE_BIT: u8 = 0x01;
    pub const ROOT_HINT: u8 = 0x08;
    pub const OUTSIDE_GLUE: u8 = 0x20;
    pub const CACHE_NA_ADDITIONAL: u8 = 0x31;
    pub const CACHE_NA_AUTHORITY: u8 = 0x41;
    pub const CACHE_A_ADDITIONAL: u8 = 0x51;
    pub const CACHE_NA_ANSWER: u8 = 0x61;
    pub const CACHE_A_AUTHORITY: u8 = 0x71;
    pub const CACHE_A_ANSWER: u8 = 0xC1;
    pub const GLUE: u8 = 0x80;
    pub const NS_GLUE: u8 = 0x82;
    /// The record is authoritative zone data — what you see on a DC's own zone.
    pub const ZONE: u8 = 0xF0;
}

/// The type-specific half of a record.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RecordData {
    A(Ipv4Addr),
    Aaaa(Ipv6Addr),
    Ns(String),
    Cname(String),
    Ptr(String),
    Soa {
        serial: u32,
        refresh: u32,
        retry: u32,
        expire: u32,
        minimum_ttl: u32,
        primary_server: String,
        responsible_party: String,
    },
    Mx {
        preference: u16,
        exchange: String,
    },
    Srv {
        priority: u16,
        weight: u16,
        port: u16,
        target: String,
    },
    Txt(Vec<String>),
    /// `DNS_TYPE_ZERO` — a tombstone. The payload is the entombed time as a FILETIME.
    Tombstone(u64),
    /// Any other record type, kept verbatim so a round-trip is lossless.
    Unknown {
        ty: u16,
        bytes: Vec<u8>,
    },
}

impl RecordData {
    /// The `DNS_RECORD_TYPE` code this data belongs to.
    pub fn record_type(&self) -> u16 {
        match self {
            RecordData::A(_) => ty::A,
            RecordData::Aaaa(_) => ty::AAAA,
            RecordData::Ns(_) => ty::NS,
            RecordData::Cname(_) => ty::CNAME,
            RecordData::Ptr(_) => ty::PTR,
            RecordData::Soa { .. } => ty::SOA,
            RecordData::Mx { .. } => ty::MX,
            RecordData::Srv { .. } => ty::SRV,
            RecordData::Txt(_) => ty::TXT,
            RecordData::Tombstone(_) => ty::ZERO,
            RecordData::Unknown { ty, .. } => *ty,
        }
    }

    /// Encode just the data half (what `wDataLength` counts).
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut out = Vec::new();
        match self {
            RecordData::A(ip) => out.extend_from_slice(&ip.octets()),
            RecordData::Aaaa(ip) => out.extend_from_slice(&ip.octets()),
            RecordData::Ns(n) | RecordData::Cname(n) | RecordData::Ptr(n) => {
                write_count_name(&mut out, n)
            }
            RecordData::Soa {
                serial,
                refresh,
                retry,
                expire,
                minimum_ttl,
                primary_server,
                responsible_party,
            } => {
                for v in [serial, refresh, retry, expire, minimum_ttl] {
                    out.extend_from_slice(&v.to_be_bytes());
                }
                write_count_name(&mut out, primary_server);
                write_count_name(&mut out, responsible_party);
            }
            RecordData::Mx {
                preference,
                exchange,
            } => {
                out.extend_from_slice(&preference.to_be_bytes());
                write_count_name(&mut out, exchange);
            }
            RecordData::Srv {
                priority,
                weight,
                port,
                target,
            } => {
                out.extend_from_slice(&priority.to_be_bytes());
                out.extend_from_slice(&weight.to_be_bytes());
                out.extend_from_slice(&port.to_be_bytes());
                write_count_name(&mut out, target);
            }
            RecordData::Txt(strings) => {
                for s in strings {
                    write_rpc_name(&mut out, s);
                }
            }
            RecordData::Tombstone(t) => out.extend_from_slice(&t.to_le_bytes()),
            RecordData::Unknown { bytes, .. } => out.extend_from_slice(bytes),
        }
        out
    }

    fn parse(ty: u16, b: &[u8]) -> Result<RecordData> {
        let short = || DnsError::ShortData { ty, len: b.len() };
        Ok(match ty {
            ty::A => {
                let o: [u8; 4] = b.get(..4).ok_or_else(short)?.try_into().unwrap();
                RecordData::A(Ipv4Addr::from(o))
            }
            ty::AAAA => {
                let o: [u8; 16] = b.get(..16).ok_or_else(short)?.try_into().unwrap();
                RecordData::Aaaa(Ipv6Addr::from(o))
            }
            ty::NS => RecordData::Ns(read_count_name(b, &mut 0)?),
            ty::CNAME => RecordData::Cname(read_count_name(b, &mut 0)?),
            ty::PTR => RecordData::Ptr(read_count_name(b, &mut 0)?),
            ty::SOA => {
                if b.len() < 20 {
                    return Err(short());
                }
                let be = |i: usize| u32::from_be_bytes(b[i..i + 4].try_into().unwrap());
                let mut cur = 20;
                let primary_server = read_count_name(b, &mut cur)?;
                let responsible_party = read_count_name(b, &mut cur)?;
                RecordData::Soa {
                    serial: be(0),
                    refresh: be(4),
                    retry: be(8),
                    expire: be(12),
                    minimum_ttl: be(16),
                    primary_server,
                    responsible_party,
                }
            }
            ty::MX => {
                if b.len() < 2 {
                    return Err(short());
                }
                let mut cur = 2;
                RecordData::Mx {
                    preference: u16::from_be_bytes(b[..2].try_into().unwrap()),
                    exchange: read_count_name(b, &mut cur)?,
                }
            }
            ty::SRV => {
                if b.len() < 6 {
                    return Err(short());
                }
                let be = |i: usize| u16::from_be_bytes(b[i..i + 2].try_into().unwrap());
                let mut cur = 6;
                RecordData::Srv {
                    priority: be(0),
                    weight: be(2),
                    port: be(4),
                    target: read_count_name(b, &mut cur)?,
                }
            }
            ty::TXT => {
                let mut cur = 0;
                let mut strings = Vec::new();
                while cur < b.len() {
                    strings.push(read_rpc_name(b, &mut cur)?);
                }
                RecordData::Txt(strings)
            }
            ty::ZERO => {
                let o: [u8; 8] = b.get(..8).ok_or_else(short)?.try_into().unwrap();
                RecordData::Tombstone(u64::from_le_bytes(o))
            }
            _ => RecordData::Unknown {
                ty,
                bytes: b.to_vec(),
            },
        })
    }
}

/// One `dnsRecord` attribute value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DnsRecord {
    pub version: u8,
    /// See [`rank`]; authoritative zone data is [`rank::ZONE`].
    pub rank: u8,
    pub flags: u16,
    /// Zone serial the record was last written with.
    pub serial: u32,
    /// TTL in seconds (stored big-endian, unlike every other integer in the header).
    pub ttl: u32,
    pub reserved: u32,
    /// Hours since 1601-01-01 UTC for a dynamic record; `0` means the record is static and
    /// will never be scavenged. See [`DnsRecord::timestamp_unix`].
    pub timestamp: u32,
    pub data: RecordData,
}

impl DnsRecord {
    /// A static, zone-authoritative record with a 1-hour TTL.
    pub fn new(data: RecordData) -> Self {
        DnsRecord {
            version: VERSION,
            rank: rank::ZONE,
            flags: 0,
            serial: 1,
            ttl: 3600,
            reserved: 0,
            timestamp: 0,
            data,
        }
    }

    pub fn with_ttl(mut self, ttl: u32) -> Self {
        self.ttl = ttl;
        self
    }

    pub fn with_serial(mut self, serial: u32) -> Self {
        self.serial = serial;
        self
    }

    /// The `DNS_RECORD_TYPE` code.
    pub fn record_type(&self) -> u16 {
        self.data.record_type()
    }

    /// `true` if the record is static — no timestamp, so scavenging leaves it alone.
    pub fn is_static(&self) -> bool {
        self.timestamp == 0
    }

    /// The timestamp as Unix seconds, or `None` for a static record.
    pub fn timestamp_unix(&self) -> Option<i64> {
        (self.timestamp != 0).then(|| self.timestamp as i64 * 3600 - 11_644_473_600)
    }

    /// Parse one `dnsRecord` value.
    pub fn parse(b: &[u8]) -> Result<DnsRecord> {
        if b.len() < HEADER_LEN {
            return Err(DnsError::Truncated(0));
        }
        let u16le = |i: usize| u16::from_le_bytes(b[i..i + 2].try_into().unwrap());
        let u32le = |i: usize| u32::from_le_bytes(b[i..i + 4].try_into().unwrap());

        let data_len = u16le(0) as usize;
        let ty = u16le(2);
        let body = b.get(HEADER_LEN..).unwrap_or_default();
        if body.len() < data_len {
            return Err(DnsError::BadDataLength {
                claimed: data_len,
                actual: body.len(),
            });
        }

        Ok(DnsRecord {
            version: b[4],
            rank: b[5],
            flags: u16le(6),
            serial: u32le(8),
            // The one big-endian field in the header.
            ttl: u32::from_be_bytes(b[12..16].try_into().unwrap()),
            reserved: u32le(16),
            timestamp: u32le(20),
            data: RecordData::parse(ty, &body[..data_len])?,
        })
    }

    /// Encode back to the on-wire `dnsRecord` value.
    pub fn to_bytes(&self) -> Vec<u8> {
        let data = self.data.to_bytes();
        let mut out = Vec::with_capacity(HEADER_LEN + data.len());
        out.extend_from_slice(&(data.len() as u16).to_le_bytes());
        out.extend_from_slice(&self.record_type().to_le_bytes());
        out.push(self.version);
        out.push(self.rank);
        out.extend_from_slice(&self.flags.to_le_bytes());
        out.extend_from_slice(&self.serial.to_le_bytes());
        out.extend_from_slice(&self.ttl.to_be_bytes());
        out.extend_from_slice(&self.reserved.to_le_bytes());
        out.extend_from_slice(&self.timestamp.to_le_bytes());
        out.extend_from_slice(&data);
        out
    }
}