v0.1.0
This commit is contained in:
commit
fa432bebda
189 files changed
+26219
No files matched your search
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
name = "dns-core"
|
||||
description = "EasyDNS core: protocol helpers, zone files, TSIG, DNS client"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
hickory-proto.workspace = true
|
||||
tokio.workspace = true
|
||||
hyper.workspace = true
|
||||
hyper-util.workspace = true
|
||||
http-body-util.workspace = true
|
||||
bytes.workspace = true
|
||||
thiserror.workspace = true
|
||||
tracing.workspace = true
|
||||
rand.workspace = true
|
||||
data-encoding.workspace = true
|
||||
serde.workspace = true
|
||||
rustls.workspace = true
|
||||
tokio-rustls.workspace = true
|
||||
webpki-roots.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
rcgen.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Resolution result shared by the cache, recursive resolver, forwarder and server.
|
||||
use hickory_proto::op::ResponseCode;
|
||||
use hickory_proto::rr::Record;
|
||||
|
||||
/// DNSSEC validation state (RFC 4035 §4.3).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Security {
|
||||
Secure,
|
||||
Insecure,
|
||||
Bogus,
|
||||
#[default]
|
||||
Indeterminate,
|
||||
}
|
||||
|
||||
/// Where an answer came from (for logging/metrics; low cardinality).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Source {
|
||||
Authoritative,
|
||||
Cache,
|
||||
Recursive,
|
||||
Forward,
|
||||
Blocked,
|
||||
Local,
|
||||
Refused,
|
||||
}
|
||||
|
||||
impl Source {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Source::Authoritative => "authoritative",
|
||||
Source::Cache => "cache",
|
||||
Source::Recursive => "recursive",
|
||||
Source::Forward => "forward",
|
||||
Source::Blocked => "blocked",
|
||||
Source::Local => "local",
|
||||
Source::Refused => "refused",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A resolved answer.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Answer {
|
||||
pub rcode: ResponseCode,
|
||||
pub answers: Vec<Record>,
|
||||
pub authority: Vec<Record>,
|
||||
pub additional: Vec<Record>,
|
||||
pub security: Security,
|
||||
pub source: Source,
|
||||
/// Free-form note (upstream used, block reason) for logs.
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
impl Answer {
|
||||
pub fn new(rcode: ResponseCode, source: Source) -> Self {
|
||||
Self {
|
||||
rcode,
|
||||
answers: Vec::new(),
|
||||
authority: Vec::new(),
|
||||
additional: Vec::new(),
|
||||
security: Security::Indeterminate,
|
||||
source,
|
||||
note: None,
|
||||
}
|
||||
}
|
||||
pub fn servfail(source: Source, note: impl Into<String>) -> Self {
|
||||
let mut a = Self::new(ResponseCode::ServFail, source);
|
||||
a.note = Some(note.into());
|
||||
a
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
//! Async DNS client: UDP with TCP fallback, TCP streams and zone transfers.
|
||||
//!
|
||||
//! Anti-spoofing measures: random 16-bit IDs, a fresh ephemeral UDP socket
|
||||
//! (random source port) per exchange, `connect()`ed sockets so only the server
|
||||
//! address is accepted, and question matching on every response.
|
||||
use std::net::SocketAddr;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use hickory_proto::op::{Edns, Message, MessageType, OpCode, Query, ResponseCode};
|
||||
use hickory_proto::rr::{DNSClass, Name, RData, Record, RecordType};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpStream, UdpSocket};
|
||||
|
||||
use crate::tsig::{ResponseVerifier, TsigKey};
|
||||
use crate::wire::{DEFAULT_EDNS_PAYLOAD, response_matches};
|
||||
use crate::{CoreError, CoreResult};
|
||||
|
||||
/// Transport actually used for an exchange.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Transport {
|
||||
Udp,
|
||||
Tcp,
|
||||
}
|
||||
|
||||
/// Options for a single query.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct QueryOptions {
|
||||
pub timeout: Duration,
|
||||
pub retries: u32,
|
||||
pub tcp_only: bool,
|
||||
/// Do not retry over TCP when the UDP answer is truncated.
|
||||
pub ignore_tc: bool,
|
||||
pub edns: bool,
|
||||
pub edns_payload: u16,
|
||||
pub dnssec_ok: bool,
|
||||
pub recursion_desired: bool,
|
||||
pub checking_disabled: bool,
|
||||
pub tsig: Option<TsigKey>,
|
||||
}
|
||||
|
||||
impl Default for QueryOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
timeout: Duration::from_secs(2),
|
||||
retries: 2,
|
||||
tcp_only: false,
|
||||
ignore_tc: false,
|
||||
edns: true,
|
||||
edns_payload: DEFAULT_EDNS_PAYLOAD,
|
||||
dnssec_ok: false,
|
||||
recursion_desired: true,
|
||||
checking_disabled: false,
|
||||
tsig: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A completed exchange.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Exchange {
|
||||
pub server: SocketAddr,
|
||||
pub message: Message,
|
||||
pub transport: Transport,
|
||||
pub elapsed: Duration,
|
||||
pub size: usize,
|
||||
pub tsig_verified: bool,
|
||||
}
|
||||
|
||||
/// Build a query message with a random ID.
|
||||
pub fn build_query(name: &Name, rtype: RecordType, opts: &QueryOptions) -> Message {
|
||||
let mut m = Message::new(rand::random::<u16>(), MessageType::Query, OpCode::Query);
|
||||
m.metadata.recursion_desired = opts.recursion_desired;
|
||||
m.metadata.checking_disabled = opts.checking_disabled;
|
||||
let mut q = Query::query(name.clone(), rtype);
|
||||
q.set_query_class(DNSClass::IN);
|
||||
m.add_query(q);
|
||||
if opts.edns {
|
||||
let mut e = Edns::new();
|
||||
e.set_max_payload(opts.edns_payload.max(512));
|
||||
e.set_dnssec_ok(opts.dnssec_ok);
|
||||
m.set_edns(e);
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Query `server` for `name`/`rtype`.
|
||||
pub async fn query(server: SocketAddr, name: &Name, rtype: RecordType, opts: &QueryOptions) -> CoreResult<Exchange> {
|
||||
let msg = build_query(name, rtype, opts);
|
||||
exchange(server, msg, opts).await
|
||||
}
|
||||
|
||||
/// Send a prepared message (signing it with TSIG if configured), with retries and
|
||||
/// automatic UDP→TCP fallback on truncation.
|
||||
pub async fn exchange(server: SocketAddr, mut msg: Message, opts: &QueryOptions) -> CoreResult<Exchange> {
|
||||
let req_mac = match &opts.tsig {
|
||||
Some(k) => Some(k.sign_request(&mut msg)?),
|
||||
None => None,
|
||||
};
|
||||
let bytes = msg.to_vec()?;
|
||||
let start = Instant::now();
|
||||
let mut last_err = CoreError::Timeout(opts.timeout);
|
||||
let attempts = opts.retries + 1;
|
||||
for _ in 0..attempts {
|
||||
let res = if opts.tcp_only {
|
||||
tcp_exchange(server, &bytes, &msg, opts.timeout).await.map(|r| (r, Transport::Tcp))
|
||||
} else {
|
||||
match udp_exchange(server, &bytes, &msg, opts.timeout).await {
|
||||
Ok((_, m)) if m.metadata.truncation && !opts.ignore_tc => {
|
||||
tcp_exchange(server, &bytes, &msg, opts.timeout).await.map(|r| (r, Transport::Tcp))
|
||||
}
|
||||
Ok(r) => Ok((r, Transport::Udp)),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
};
|
||||
match res {
|
||||
Ok(((raw, m), transport)) => {
|
||||
let mut verified = false;
|
||||
if let (Some(k), Some(mac)) = (&opts.tsig, &req_mac) {
|
||||
let mut v = ResponseVerifier::new(k.clone(), mac.clone());
|
||||
verified = v.verify(&raw, &m)?;
|
||||
if !verified {
|
||||
return Err(CoreError::Tsig("response is not signed".into()));
|
||||
}
|
||||
}
|
||||
return Ok(Exchange { server, size: raw.len(), message: m, transport, elapsed: start.elapsed(), tsig_verified: verified });
|
||||
}
|
||||
Err(e @ CoreError::Tsig(_)) => return Err(e),
|
||||
Err(e) => last_err = e,
|
||||
}
|
||||
}
|
||||
Err(last_err)
|
||||
}
|
||||
|
||||
async fn udp_exchange(server: SocketAddr, bytes: &[u8], query: &Message, timeout: Duration) -> CoreResult<(Vec<u8>, Message)> {
|
||||
let bind: SocketAddr = if server.is_ipv4() {
|
||||
"0.0.0.0:0".parse().map_err(|_| CoreError::Invalid("bind".into()))?
|
||||
} else {
|
||||
"[::]:0".parse().map_err(|_| CoreError::Invalid("bind".into()))?
|
||||
};
|
||||
let sock = UdpSocket::bind(bind).await?;
|
||||
sock.connect(server).await?;
|
||||
sock.send(bytes).await?;
|
||||
let deadline = Instant::now() + timeout;
|
||||
let mut buf = vec![0u8; 65_535];
|
||||
loop {
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
if remaining.is_zero() {
|
||||
return Err(CoreError::Timeout(timeout));
|
||||
}
|
||||
let n = match tokio::time::timeout(remaining, sock.recv(&mut buf)).await {
|
||||
Ok(r) => r?,
|
||||
Err(_) => return Err(CoreError::Timeout(timeout)),
|
||||
};
|
||||
let raw = &buf[..n];
|
||||
let Ok(m) = Message::from_vec(raw) else { continue };
|
||||
if response_matches(query, &m) {
|
||||
return Ok((raw.to_vec(), m));
|
||||
}
|
||||
// Mismatched ID/question: ignore (possible spoofing attempt) and keep waiting.
|
||||
tracing::debug!(%server, "ignoring mismatched UDP response");
|
||||
}
|
||||
}
|
||||
|
||||
async fn tcp_exchange(server: SocketAddr, bytes: &[u8], query: &Message, timeout: Duration) -> CoreResult<(Vec<u8>, Message)> {
|
||||
let fut = async {
|
||||
let mut s = TcpStream::connect(server).await?;
|
||||
s.set_nodelay(true)?;
|
||||
write_tcp_msg(&mut s, bytes).await?;
|
||||
let raw = read_tcp_msg(&mut s).await?;
|
||||
let m = Message::from_vec(&raw).map_err(|e| CoreError::Proto(e.to_string()))?;
|
||||
if !response_matches(query, &m) {
|
||||
return Err(CoreError::Mismatch("TCP response does not match query".into()));
|
||||
}
|
||||
Ok((raw, m))
|
||||
};
|
||||
tokio::time::timeout(timeout, fut).await.map_err(|_| CoreError::Timeout(timeout))?
|
||||
}
|
||||
|
||||
/// Write a 2-byte length-prefixed DNS message.
|
||||
pub async fn write_tcp_msg<W: AsyncWriteExt + Unpin>(w: &mut W, bytes: &[u8]) -> CoreResult<()> {
|
||||
if bytes.len() > u16::MAX as usize {
|
||||
return Err(CoreError::Invalid("message too large for TCP".into()));
|
||||
}
|
||||
let mut buf = Vec::with_capacity(bytes.len() + 2);
|
||||
buf.extend_from_slice(&(bytes.len() as u16).to_be_bytes());
|
||||
buf.extend_from_slice(bytes);
|
||||
w.write_all(&buf).await?;
|
||||
w.flush().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read a 2-byte length-prefixed DNS message.
|
||||
pub async fn read_tcp_msg<R: AsyncReadExt + Unpin>(r: &mut R) -> CoreResult<Vec<u8>> {
|
||||
let mut len = [0u8; 2];
|
||||
r.read_exact(&mut len).await?;
|
||||
let len = u16::from_be_bytes(len) as usize;
|
||||
if len < 12 {
|
||||
return Err(CoreError::Proto("TCP message shorter than DNS header".into()));
|
||||
}
|
||||
let mut buf = vec![0u8; len];
|
||||
r.read_exact(&mut buf).await?;
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
/// Kind of zone transfer.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum TransferKind {
|
||||
Axfr,
|
||||
/// IXFR from the given client SOA (RFC 1995: SOA goes in the authority section).
|
||||
Ixfr {
|
||||
current_soa: Box<Record>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Result of a zone transfer: the flat record stream as received.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TransferStream {
|
||||
pub records: Vec<Record>,
|
||||
pub messages: usize,
|
||||
pub bytes: usize,
|
||||
pub tsig_verified: bool,
|
||||
pub elapsed: Duration,
|
||||
}
|
||||
|
||||
/// Limits applied to an incoming transfer.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct TransferLimits {
|
||||
pub timeout: Duration,
|
||||
pub max_records: usize,
|
||||
pub max_bytes: usize,
|
||||
}
|
||||
|
||||
impl Default for TransferLimits {
|
||||
fn default() -> Self {
|
||||
Self { timeout: Duration::from_secs(120), max_records: 2_000_000, max_bytes: 512 * 1024 * 1024 }
|
||||
}
|
||||
}
|
||||
|
||||
fn soa_serial(r: &Record) -> Option<u32> {
|
||||
match &r.data {
|
||||
RData::SOA(s) => Some(s.serial),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Perform an AXFR/IXFR over TCP and return the record stream. The stream is
|
||||
/// complete (terminating SOA seen) when this returns `Ok`.
|
||||
pub async fn transfer(
|
||||
server: SocketAddr,
|
||||
zone: &Name,
|
||||
kind: &TransferKind,
|
||||
tsig: Option<&TsigKey>,
|
||||
limits: TransferLimits,
|
||||
) -> CoreResult<TransferStream> {
|
||||
let start = Instant::now();
|
||||
let rtype = match kind {
|
||||
TransferKind::Axfr => RecordType::AXFR,
|
||||
TransferKind::Ixfr { .. } => RecordType::IXFR,
|
||||
};
|
||||
let mut msg = Message::new(rand::random::<u16>(), MessageType::Query, OpCode::Query);
|
||||
msg.add_query(Query::query(zone.clone(), rtype));
|
||||
let client_serial = if let TransferKind::Ixfr { current_soa } = kind {
|
||||
let soa: &Record = current_soa;
|
||||
msg.add_authority(soa.clone());
|
||||
soa_serial(current_soa)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let req_mac = match tsig {
|
||||
Some(k) => Some(k.sign_request(&mut msg)?),
|
||||
None => None,
|
||||
};
|
||||
let bytes = msg.to_vec()?;
|
||||
let mut verifier = match (tsig, req_mac) {
|
||||
(Some(k), Some(mac)) => Some(ResponseVerifier::new(k.clone(), mac)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let fut = async {
|
||||
let mut s = TcpStream::connect(server).await?;
|
||||
s.set_nodelay(true)?;
|
||||
write_tcp_msg(&mut s, &bytes).await?;
|
||||
let mut records: Vec<Record> = Vec::new();
|
||||
let mut messages = 0usize;
|
||||
let mut total = 0usize;
|
||||
let mut final_serial: Option<u32> = None;
|
||||
let mut incremental: Option<bool> = None;
|
||||
let mut final_soa_seen = 0usize;
|
||||
loop {
|
||||
let raw = read_tcp_msg(&mut s).await?;
|
||||
total += raw.len();
|
||||
if total > limits.max_bytes {
|
||||
return Err(CoreError::Transfer("transfer exceeds byte limit".into()));
|
||||
}
|
||||
let m = Message::from_vec(&raw).map_err(|e| CoreError::Proto(e.to_string()))?;
|
||||
if m.metadata.id != msg.metadata.id || m.metadata.message_type != MessageType::Response {
|
||||
return Err(CoreError::Mismatch("transfer response id mismatch".into()));
|
||||
}
|
||||
if let Some(v) = verifier.as_mut() {
|
||||
v.verify(&raw, &m)?;
|
||||
}
|
||||
if m.metadata.response_code != ResponseCode::NoError {
|
||||
return Err(CoreError::Transfer(format!("server answered {}", m.metadata.response_code)));
|
||||
}
|
||||
messages += 1;
|
||||
for r in m.answers {
|
||||
if records.is_empty() {
|
||||
let Some(s) = soa_serial(&r) else {
|
||||
return Err(CoreError::Transfer("first transfer record is not SOA".into()));
|
||||
};
|
||||
final_serial = Some(s);
|
||||
final_soa_seen = 1;
|
||||
} else {
|
||||
if records.len() == 1 {
|
||||
incremental = Some(rtype == RecordType::IXFR && r.record_type() == RecordType::SOA);
|
||||
}
|
||||
if soa_serial(&r) == final_serial {
|
||||
final_soa_seen += 1;
|
||||
}
|
||||
}
|
||||
records.push(r);
|
||||
if records.len() > limits.max_records {
|
||||
return Err(CoreError::Transfer("transfer exceeds record limit".into()));
|
||||
}
|
||||
}
|
||||
// Termination conditions.
|
||||
let done = match (records.len(), incremental) {
|
||||
(0, _) => false,
|
||||
// Single SOA: IXFR "up to date" reply when serial is not newer.
|
||||
(1, _) => {
|
||||
rtype == RecordType::IXFR
|
||||
&& match (final_serial, client_serial) {
|
||||
(Some(f), Some(c)) => !crate::serial::is_newer(f, c),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
(_, Some(true)) => final_soa_seen >= 3 && records.last().and_then(soa_serial) == final_serial,
|
||||
(_, _) => final_soa_seen >= 2 && records.last().and_then(soa_serial) == final_serial,
|
||||
};
|
||||
if done {
|
||||
if let Some(v) = &verifier {
|
||||
v.finish()?;
|
||||
}
|
||||
return Ok(TransferStream { records, messages, bytes: total, tsig_verified: verifier.is_some(), elapsed: start.elapsed() });
|
||||
}
|
||||
}
|
||||
};
|
||||
tokio::time::timeout(limits.timeout, fut).await.map_err(|_| CoreError::Timeout(limits.timeout))?
|
||||
}
|
||||
|
||||
/// Send a NOTIFY for `zone` (optionally carrying the new SOA) and wait for the ack.
|
||||
pub async fn notify(
|
||||
server: SocketAddr,
|
||||
zone: &Name,
|
||||
soa: Option<&Record>,
|
||||
tsig: Option<&TsigKey>,
|
||||
timeout: Duration,
|
||||
) -> CoreResult<ResponseCode> {
|
||||
let mut m = Message::new(rand::random::<u16>(), MessageType::Query, OpCode::Notify);
|
||||
m.metadata.authoritative = true;
|
||||
m.add_query(Query::query(zone.clone(), RecordType::SOA));
|
||||
if let Some(s) = soa {
|
||||
m.add_answer(s.clone());
|
||||
}
|
||||
let opts = QueryOptions { timeout, retries: 2, edns: false, recursion_desired: false, tsig: tsig.cloned(), ..Default::default() };
|
||||
let ex = exchange(server, m, &opts).await?;
|
||||
Ok(ex.message.metadata.response_code)
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
//! DNSSEC primitives shared by the signer (primary) and the validator (resolver, ednssec):
|
||||
//! key generation/loading, RRset signing, RRSIG verification, DS matching and
|
||||
//! NSEC/NSEC3 denial-of-existence checks (RFC 4033–4035, RFC 5155).
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use data_encoding::{BASE32_DNSSEC, BASE64};
|
||||
use hickory_proto::dnssec::crypto::{EcdsaSigningKey, Ed25519SigningKey};
|
||||
use hickory_proto::dnssec::rdata::{DNSKEY, DNSSECRData, DS, NSEC, NSEC3, RRSIG, SigInput};
|
||||
use hickory_proto::dnssec::{Algorithm, DigestType, Nsec3HashAlgorithm, SigningKey, TBS, Verifier};
|
||||
use hickory_proto::rr::{DNSClass, Name, RData, Record, RecordType, SerialNumber};
|
||||
use rustls::pki_types::PrivatePkcs8KeyDer;
|
||||
|
||||
use crate::{CoreError, CoreResult};
|
||||
|
||||
/// Supported signing algorithms.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum KeyAlgorithm {
|
||||
#[default]
|
||||
Ed25519,
|
||||
Ecdsap256,
|
||||
Ecdsap384,
|
||||
}
|
||||
|
||||
impl KeyAlgorithm {
|
||||
pub fn dnssec(self) -> Algorithm {
|
||||
match self {
|
||||
KeyAlgorithm::Ed25519 => Algorithm::ED25519,
|
||||
KeyAlgorithm::Ecdsap256 => Algorithm::ECDSAP256SHA256,
|
||||
KeyAlgorithm::Ecdsap384 => Algorithm::ECDSAP384SHA384,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A private key with its public DNSKEY.
|
||||
pub struct ZoneKey {
|
||||
pub dnskey: DNSKEY,
|
||||
pub tag: u16,
|
||||
pub ksk: bool,
|
||||
signing: Box<dyn SigningKey>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ZoneKey {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "ZoneKey(tag {}, {}, {:?})", self.tag, if self.ksk { "KSK" } else { "ZSK" }, self.dnskey.algorithm())
|
||||
}
|
||||
}
|
||||
|
||||
fn signer(alg: KeyAlgorithm, pkcs8: &[u8]) -> CoreResult<Box<dyn SigningKey>> {
|
||||
let der = PrivatePkcs8KeyDer::from(pkcs8.to_vec());
|
||||
let k: Box<dyn SigningKey> = match alg {
|
||||
KeyAlgorithm::Ed25519 => Box::new(Ed25519SigningKey::from_pkcs8(&der).map_err(|e| CoreError::Invalid(e.to_string()))?),
|
||||
a => Box::new(EcdsaSigningKey::from_pkcs8(&der, a.dnssec()).map_err(|e| CoreError::Invalid(e.to_string()))?),
|
||||
};
|
||||
Ok(k)
|
||||
}
|
||||
|
||||
impl ZoneKey {
|
||||
/// Generate a new key; returns the PKCS#8 private key bytes and the key.
|
||||
pub fn generate(alg: KeyAlgorithm, ksk: bool) -> CoreResult<(Vec<u8>, Self)> {
|
||||
let der = match alg {
|
||||
KeyAlgorithm::Ed25519 => Ed25519SigningKey::generate_pkcs8(),
|
||||
a => EcdsaSigningKey::generate_pkcs8(a.dnssec()),
|
||||
}
|
||||
.map_err(|e| CoreError::Invalid(e.to_string()))?;
|
||||
let bytes = der.secret_pkcs8_der().to_vec();
|
||||
let k = Self::from_pkcs8(alg, &bytes, ksk)?;
|
||||
Ok((bytes, k))
|
||||
}
|
||||
|
||||
pub fn from_pkcs8(alg: KeyAlgorithm, pkcs8: &[u8], ksk: bool) -> CoreResult<Self> {
|
||||
let signing = signer(alg, pkcs8)?;
|
||||
let public = signing.to_public_key().map_err(|e| CoreError::Invalid(e.to_string()))?;
|
||||
let dnskey = DNSKEY::new(true, ksk, false, public);
|
||||
let tag = dnskey.calculate_key_tag().map_err(|e| CoreError::Invalid(e.to_string()))?;
|
||||
Ok(Self { dnskey, tag, ksk, signing })
|
||||
}
|
||||
|
||||
/// DNSKEY record for the zone apex.
|
||||
pub fn dnskey_record(&self, zone: &Name, ttl: u32) -> Record {
|
||||
Record::from_rdata(zone.clone(), ttl, RData::DNSSEC(DNSSECRData::DNSKEY(self.dnskey.clone())))
|
||||
}
|
||||
|
||||
/// DS record (SHA-256) to publish in the parent zone.
|
||||
pub fn ds_record(&self, zone: &Name, ttl: u32) -> CoreResult<Record> {
|
||||
let digest = self.dnskey.to_digest(zone, DigestType::SHA256).map_err(|e| CoreError::Invalid(e.to_string()))?;
|
||||
let ds = DS::new(self.tag, self.dnskey.algorithm(), DigestType::SHA256, digest.as_ref().to_vec());
|
||||
Ok(Record::from_rdata(zone.clone(), ttl, RData::DNSSEC(DNSSECRData::DS(ds))))
|
||||
}
|
||||
|
||||
/// Sign an RRset (all records must share owner/type/class). `zone` is the signer name.
|
||||
pub fn sign(&self, zone: &Name, rrset: &[Record], inception: u32, expiration: u32) -> CoreResult<Record> {
|
||||
let first = rrset.first().ok_or_else(|| CoreError::Invalid("empty RRset".into()))?;
|
||||
let labels = if first.name.is_wildcard() { first.name.num_labels() - 1 } else { first.name.num_labels() };
|
||||
let ttl = rrset.iter().map(|r| r.ttl).min().unwrap_or(first.ttl);
|
||||
let input = SigInput {
|
||||
type_covered: first.record_type(),
|
||||
algorithm: self.dnskey.algorithm(),
|
||||
num_labels: labels,
|
||||
original_ttl: ttl,
|
||||
sig_expiration: SerialNumber::new(expiration),
|
||||
sig_inception: SerialNumber::new(inception),
|
||||
key_tag: self.tag,
|
||||
signer_name: zone.clone(),
|
||||
};
|
||||
let tbs = TBS::from_input(&first.name, first.dns_class, &input, rrset.iter()).map_err(|e| CoreError::Invalid(e.to_string()))?;
|
||||
let sig = self.signing.sign(&tbs).map_err(|e| CoreError::Invalid(e.to_string()))?;
|
||||
let rrsig = RRSIG::from_sig(input, sig);
|
||||
let mut r = Record::from_rdata(first.name.clone(), ttl, RData::DNSSEC(DNSSECRData::RRSIG(rrsig)));
|
||||
r.dns_class = first.dns_class;
|
||||
Ok(r)
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialise a private key for storage (`<zone>.<tag>.<ksk|zsk>.key`).
|
||||
pub fn key_file_contents(alg: KeyAlgorithm, ksk: bool, pkcs8: &[u8]) -> String {
|
||||
format!(
|
||||
"; EasyDNS DNSSEC private key – keep secret\nalgorithm: {}\nflags: {}\npkcs8: {}\n",
|
||||
serde_json::to_value(alg).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default(),
|
||||
if ksk { 257 } else { 256 },
|
||||
BASE64.encode(pkcs8)
|
||||
)
|
||||
}
|
||||
|
||||
/// Parse a stored private key.
|
||||
pub fn parse_key_file(text: &str) -> CoreResult<ZoneKey> {
|
||||
let mut alg = None;
|
||||
let mut ksk = false;
|
||||
let mut pk = None;
|
||||
for l in text.lines().map(str::trim).filter(|l| !l.starts_with(';') && !l.is_empty()) {
|
||||
let Some((k, v)) = l.split_once(':') else { continue };
|
||||
match k.trim() {
|
||||
"algorithm" => alg = serde_json::from_value::<KeyAlgorithm>(serde_json::Value::String(v.trim().into())).ok(),
|
||||
"flags" => ksk = v.trim() == "257",
|
||||
"pkcs8" => pk = BASE64.decode(v.trim().as_bytes()).ok(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (Some(alg), Some(pk)) = (alg, pk) else {
|
||||
return Err(CoreError::Invalid("key file must contain algorithm and pkcs8".into()));
|
||||
};
|
||||
ZoneKey::from_pkcs8(alg, &pk, ksk)
|
||||
}
|
||||
|
||||
fn rrsig_of(r: &Record) -> Option<&RRSIG> {
|
||||
match &r.data {
|
||||
RData::DNSSEC(DNSSECRData::RRSIG(s)) => Some(s),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dnskey_of(r: &Record) -> Option<&DNSKEY> {
|
||||
match &r.data {
|
||||
RData::DNSSEC(DNSSECRData::DNSKEY(k)) => Some(k),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ds_of(r: &Record) -> Option<&DS> {
|
||||
match &r.data {
|
||||
RData::DNSSEC(DNSSECRData::DS(d)) => Some(d),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Signer name and covered type of an RRSIG record.
|
||||
pub fn rrsig_info(r: &Record) -> Option<(Name, RecordType, u16)> {
|
||||
rrsig_of(r).map(|s| (s.input().signer_name.clone(), s.input().type_covered, s.input().key_tag))
|
||||
}
|
||||
|
||||
/// Algorithms we can verify.
|
||||
pub fn algorithm_supported(a: Algorithm) -> bool {
|
||||
matches!(a, Algorithm::RSASHA256 | Algorithm::RSASHA512 | Algorithm::ECDSAP256SHA256 | Algorithm::ECDSAP384SHA384 | Algorithm::ED25519)
|
||||
}
|
||||
|
||||
/// Verify that `rrset` is signed by one of `rrsigs` using one of `keys`, at time `now`.
|
||||
/// Returns the key tag that validated. RFC 4035 §5.3.
|
||||
pub fn verify_rrset(owner: &Name, rrset: &[Record], rrsigs: &[Record], keys: &[DNSKEY], signer: &Name, now: u32) -> Result<u16, String> {
|
||||
let Some(first) = rrset.first() else { return Err("empty RRset".into()) };
|
||||
let rtype = first.record_type();
|
||||
let mut errors = Vec::new();
|
||||
for r in rrsigs {
|
||||
let Some(sig) = rrsig_of(r) else { continue };
|
||||
let i = sig.input();
|
||||
if i.type_covered != rtype || !r.name.eq_ignore_root_case(owner) {
|
||||
continue;
|
||||
}
|
||||
if !i.signer_name.eq_ignore_root_case(signer) || !signer.zone_of(owner) {
|
||||
errors.push(format!("RRSIG signer {} is not the zone {signer}", i.signer_name));
|
||||
continue;
|
||||
}
|
||||
let (inc, exp) = (i.sig_inception.get(), i.sig_expiration.get());
|
||||
if crate::serial::is_newer(inc, now) {
|
||||
errors.push(format!("RRSIG not yet valid (inception {inc})"));
|
||||
continue;
|
||||
}
|
||||
if crate::serial::is_newer(now, exp) {
|
||||
errors.push(format!("RRSIG expired (expiration {exp})"));
|
||||
continue;
|
||||
}
|
||||
if u32::from(i.num_labels) > owner.num_labels() as u32 {
|
||||
errors.push("RRSIG labels field larger than owner".into());
|
||||
continue;
|
||||
}
|
||||
for k in keys.iter().filter(|k| k.zone_key() && !k.revoke() && k.algorithm() == i.algorithm) {
|
||||
if k.calculate_key_tag().ok() != Some(i.key_tag) {
|
||||
continue;
|
||||
}
|
||||
// RFC 4035 §5.3.3: verify using the original TTL, owner per labels field.
|
||||
let mut set: Vec<Record> = rrset.to_vec();
|
||||
for x in &mut set {
|
||||
x.ttl = i.original_ttl;
|
||||
}
|
||||
match k.verify_rrsig(owner, first.dns_class, sig, set.iter()) {
|
||||
Ok(()) => return Ok(i.key_tag),
|
||||
Err(e) => errors.push(format!("signature by key {} invalid: {e}", i.key_tag)),
|
||||
}
|
||||
}
|
||||
}
|
||||
if errors.is_empty() { Err(format!("no usable RRSIG for {owner} {rtype}")) } else { Err(errors.join("; ")) }
|
||||
}
|
||||
|
||||
/// Does `ds` match `key` for zone `owner`?
|
||||
pub fn ds_matches(ds: &DS, owner: &Name, key: &DNSKEY) -> bool {
|
||||
ds.key_tag() == key.calculate_key_tag().unwrap_or(0) && ds.algorithm() == key.algorithm() && ds.covers(owner, key).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// RFC 4034 §6.1 canonical ordering helper: is `name` strictly between `owner` and `next`
|
||||
/// (taking the wrap-around at the end of the chain into account)?
|
||||
pub fn nsec_covers(owner: &Name, next: &Name, name: &Name) -> bool {
|
||||
if owner < next {
|
||||
owner < name && name < next
|
||||
} else {
|
||||
// last NSEC in the chain: covers everything after owner (or before next)
|
||||
name > owner || name < next
|
||||
}
|
||||
}
|
||||
|
||||
/// Outcome of a denial-of-existence check.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Denial {
|
||||
/// The name does not exist (NXDOMAIN proven).
|
||||
NxDomain,
|
||||
/// The name exists but not the type (NODATA proven).
|
||||
NoData,
|
||||
/// Insecure delegation (no DS) / opt-out proven.
|
||||
InsecureDelegation,
|
||||
/// Records do not prove the claim.
|
||||
Unproven(String),
|
||||
}
|
||||
|
||||
fn nsec_of(r: &Record) -> Option<&NSEC> {
|
||||
match &r.data {
|
||||
RData::DNSSEC(DNSSECRData::NSEC(n)) => Some(n),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn nsec3_of(r: &Record) -> Option<&NSEC3> {
|
||||
match &r.data {
|
||||
RData::DNSSEC(DNSSECRData::NSEC3(n)) => Some(n),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check NSEC records (already signature-verified) for qname/qtype. `zone` is the signer.
|
||||
pub fn check_nsec(records: &[Record], qname: &Name, qtype: RecordType, zone: &Name) -> Denial {
|
||||
let nsecs: Vec<(&Record, &NSEC)> = records.iter().filter_map(|r| nsec_of(r).map(|n| (r, n))).collect();
|
||||
if nsecs.is_empty() {
|
||||
return Denial::Unproven("no NSEC records".into());
|
||||
}
|
||||
// NODATA: NSEC at qname without the type (and without CNAME)
|
||||
if let Some((_, n)) = nsecs.iter().find(|(r, _)| r.name.eq_ignore_root_case(qname)) {
|
||||
let types: BTreeSet<RecordType> = n.type_bit_maps().collect();
|
||||
if qtype == RecordType::DS {
|
||||
return if types.contains(&RecordType::DS) {
|
||||
Denial::Unproven("NSEC shows DS exists".into())
|
||||
} else if types.contains(&RecordType::NS) && !types.contains(&RecordType::SOA) {
|
||||
Denial::InsecureDelegation
|
||||
} else {
|
||||
Denial::NoData
|
||||
};
|
||||
}
|
||||
if types.contains(&qtype) || types.contains(&RecordType::CNAME) {
|
||||
return Denial::Unproven(format!("NSEC shows {qtype} exists"));
|
||||
}
|
||||
// An NSEC from the parent side of a delegation cannot prove NODATA below the cut.
|
||||
if types.contains(&RecordType::NS) && !types.contains(&RecordType::SOA) && !qname.eq_ignore_root_case(zone) {
|
||||
return Denial::Unproven("NSEC from delegation point".into());
|
||||
}
|
||||
return Denial::NoData;
|
||||
}
|
||||
// NXDOMAIN: an NSEC covers qname, and an NSEC covers the wildcard at the closest encloser.
|
||||
let covering = nsecs.iter().find(|(r, n)| nsec_covers(&r.name, n.next_domain_name(), qname));
|
||||
let Some((cov, cov_n)) = covering else {
|
||||
return Denial::Unproven(format!("no NSEC covers {qname}"));
|
||||
};
|
||||
// closest encloser = longest common ancestor of qname with owner/next of the covering NSEC
|
||||
let common = |a: &Name, b: &Name| -> usize {
|
||||
let la: Vec<_> = a.iter().rev().collect();
|
||||
let lb: Vec<_> = b.iter().rev().collect();
|
||||
la.iter().zip(lb.iter()).take_while(|(x, y)| x.eq_ignore_ascii_case(y)).count()
|
||||
};
|
||||
let ce_labels = common(qname, &cov.name).max(common(qname, cov_n.next_domain_name())).max(zone.num_labels() as usize);
|
||||
let ce = qname.trim_to(ce_labels);
|
||||
let Ok(wc) = Name::from_ascii("*").and_then(|w| w.append_domain(&ce)) else {
|
||||
return Denial::Unproven("bad wildcard".into());
|
||||
};
|
||||
let wc_denied = nsecs.iter().any(|(r, n)| {
|
||||
nsec_covers(&r.name, n.next_domain_name(), &wc) || (r.name.eq_ignore_root_case(&wc) && !n.type_bit_maps().any(|t| t == qtype))
|
||||
});
|
||||
if wc_denied || wc.eq_ignore_root_case(qname) { Denial::NxDomain } else { Denial::Unproven("wildcard not denied".into()) }
|
||||
}
|
||||
|
||||
/// RFC 5155 hash of a name, base32hex (lowercase) label.
|
||||
pub fn nsec3_hash(name: &Name, salt: &[u8], iterations: u16) -> Option<String> {
|
||||
let d = Nsec3HashAlgorithm::SHA1.hash(salt, name, iterations).ok()?;
|
||||
Some(BASE32_DNSSEC.encode(d.as_ref()).to_ascii_lowercase())
|
||||
}
|
||||
|
||||
/// Check NSEC3 records (already signature-verified). Iterations above 150 are treated as
|
||||
/// insecure per RFC 9276.
|
||||
pub fn check_nsec3(records: &[Record], qname: &Name, qtype: RecordType, zone: &Name) -> Denial {
|
||||
let n3: Vec<(String, &NSEC3)> = records
|
||||
.iter()
|
||||
.filter_map(|r| {
|
||||
nsec3_of(r).map(|n| (r.name.iter().next().map(|l| String::from_utf8_lossy(l).to_ascii_lowercase()).unwrap_or_default(), n))
|
||||
})
|
||||
.collect();
|
||||
let Some((_, p)) = n3.first() else { return Denial::Unproven("no NSEC3 records".into()) };
|
||||
if p.iterations() > 150 {
|
||||
return Denial::InsecureDelegation;
|
||||
}
|
||||
let (salt, it) = (p.salt().to_vec(), p.iterations());
|
||||
let hash = |n: &Name| nsec3_hash(n, &salt, it).unwrap_or_default();
|
||||
let next_of = |n: &NSEC3| BASE32_DNSSEC.encode(n.next_hashed_owner_name()).to_ascii_lowercase();
|
||||
let matching = |h: &str| n3.iter().find(|(o, _)| o == h).map(|(_, n)| *n);
|
||||
let covering = |h: &str| {
|
||||
n3.iter()
|
||||
.find(|(o, n)| {
|
||||
let nx = next_of(n);
|
||||
if o.as_str() < nx.as_str() { o.as_str() < h && h < nx.as_str() } else { h > o.as_str() || h < nx.as_str() }
|
||||
})
|
||||
.map(|(_, n)| *n)
|
||||
};
|
||||
let qh = hash(qname);
|
||||
if let Some(m) = matching(&qh) {
|
||||
let types: BTreeSet<RecordType> = m.type_bit_maps().collect();
|
||||
if qtype == RecordType::DS {
|
||||
if types.contains(&RecordType::DS) {
|
||||
return Denial::Unproven("NSEC3 shows DS exists".into());
|
||||
}
|
||||
return if types.contains(&RecordType::NS) && !types.contains(&RecordType::SOA) {
|
||||
Denial::InsecureDelegation
|
||||
} else {
|
||||
Denial::NoData
|
||||
};
|
||||
}
|
||||
if types.contains(&qtype) || types.contains(&RecordType::CNAME) {
|
||||
return Denial::Unproven(format!("NSEC3 shows {qtype} exists"));
|
||||
}
|
||||
return Denial::NoData;
|
||||
}
|
||||
// closest encloser proof
|
||||
let mut ce: Option<Name> = None;
|
||||
for anc in crate::names::ancestors(qname).skip(1) {
|
||||
if !zone.zone_of(&anc) {
|
||||
break;
|
||||
}
|
||||
if matching(&hash(&anc)).is_some() {
|
||||
ce = Some(anc);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(ce) = ce else { return Denial::Unproven("no closest encloser".into()) };
|
||||
let next_closer = qname.trim_to(ce.num_labels() as usize + 1);
|
||||
let Some(nc) = covering(&hash(&next_closer)) else { return Denial::Unproven("next closer name not covered".into()) };
|
||||
if qtype == RecordType::DS && nc.opt_out() {
|
||||
return Denial::InsecureDelegation;
|
||||
}
|
||||
let Ok(wc) = Name::from_ascii("*").and_then(|w| w.append_domain(&ce)) else { return Denial::Unproven("bad wildcard".into()) };
|
||||
if covering(&hash(&wc)).is_some() {
|
||||
Denial::NxDomain
|
||||
} else if nc.opt_out() {
|
||||
Denial::InsecureDelegation
|
||||
} else {
|
||||
Denial::Unproven("wildcard not denied".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Build an NSEC record.
|
||||
pub fn nsec_record(owner: &Name, next: &Name, types: impl IntoIterator<Item = RecordType>, ttl: u32) -> Record {
|
||||
Record::from_rdata(owner.clone(), ttl, RData::DNSSEC(DNSSECRData::NSEC(NSEC::new(next.clone(), types))))
|
||||
}
|
||||
|
||||
/// DNSSEC-related record type?
|
||||
pub fn is_dnssec_type(t: RecordType) -> bool {
|
||||
matches!(t, RecordType::RRSIG | RecordType::NSEC | RecordType::NSEC3 | RecordType::NSEC3PARAM | RecordType::DNSKEY)
|
||||
}
|
||||
|
||||
/// The class used everywhere.
|
||||
pub const CLASS: DNSClass = DNSClass::IN;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use hickory_proto::rr::rdata::A;
|
||||
|
||||
fn n(s: &str) -> Name {
|
||||
Name::from_ascii(s).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sign_verify_and_ds() {
|
||||
for alg in [KeyAlgorithm::Ed25519, KeyAlgorithm::Ecdsap256] {
|
||||
let zone = n("example.");
|
||||
let (pk, key) = ZoneKey::generate(alg, true).unwrap();
|
||||
let again = parse_key_file(&key_file_contents(alg, true, &pk)).unwrap();
|
||||
assert_eq!(again.tag, key.tag);
|
||||
let rrset = vec![
|
||||
Record::from_rdata(n("www.example."), 300, RData::A(A::new(192, 0, 2, 1))),
|
||||
Record::from_rdata(n("www.example."), 300, RData::A(A::new(192, 0, 2, 2))),
|
||||
];
|
||||
let now = 1_800_000_000u32;
|
||||
let sig = key.sign(&zone, &rrset, now - 100, now + 1000).unwrap();
|
||||
let keys = [key.dnskey.clone()];
|
||||
assert!(verify_rrset(&n("www.example."), &rrset, std::slice::from_ref(&sig), &keys, &zone, now).is_ok());
|
||||
// order and TTL decrements do not matter
|
||||
let mut rev = rrset.clone();
|
||||
rev.reverse();
|
||||
rev[0].ttl = 10;
|
||||
assert!(verify_rrset(&n("www.example."), &rev, std::slice::from_ref(&sig), &keys, &zone, now).is_ok());
|
||||
// tampering is detected
|
||||
let mut bad = rrset.clone();
|
||||
bad[0].data = RData::A(A::new(192, 0, 2, 99));
|
||||
assert!(verify_rrset(&n("www.example."), &bad, std::slice::from_ref(&sig), &keys, &zone, now).is_err());
|
||||
// expired
|
||||
assert!(verify_rrset(&n("www.example."), &rrset, &[sig], &keys, &zone, now + 5000).is_err());
|
||||
let ds = key.ds_record(&zone, 3600).unwrap();
|
||||
assert!(ds_matches(ds_of(&ds).unwrap(), &zone, &key.dnskey));
|
||||
assert!(!ds_matches(ds_of(&ds).unwrap(), &n("other."), &key.dnskey));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nsec_logic() {
|
||||
let z = n("example.");
|
||||
assert!(nsec_covers(&n("a.example."), &n("c.example."), &n("b.example.")));
|
||||
assert!(!nsec_covers(&n("a.example."), &n("c.example."), &n("d.example.")));
|
||||
assert!(nsec_covers(&n("x.example."), &n("example."), &n("z.example.")));
|
||||
let recs = vec![
|
||||
nsec_record(&n("example."), &n("a.example."), [RecordType::SOA, RecordType::NS], 300),
|
||||
nsec_record(&n("a.example."), &n("example."), [RecordType::A], 300),
|
||||
];
|
||||
assert_eq!(check_nsec(&recs, &n("b.example."), RecordType::A, &z), Denial::NxDomain);
|
||||
assert_eq!(check_nsec(&recs, &n("a.example."), RecordType::MX, &z), Denial::NoData);
|
||||
assert!(matches!(check_nsec(&recs, &n("a.example."), RecordType::A, &z), Denial::Unproven(_)));
|
||||
let deleg = vec![nsec_record(&n("sub.example."), &n("example."), [RecordType::NS], 300)];
|
||||
assert_eq!(check_nsec(&deleg, &n("sub.example."), RecordType::DS, &z), Denial::InsecureDelegation);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nsec3_hash_vector() {
|
||||
// RFC 5155 Appendix A: H(example) = 0p9mhaveqvm6t7vbl5lop2u3t2rp3tom (salt aabbccdd, 12 iterations)
|
||||
let h = nsec3_hash(&n("example."), &[0xaa, 0xbb, 0xcc, 0xdd], 12).unwrap();
|
||||
assert_eq!(h, "0p9mhaveqvm6t7vbl5lop2u3t2rp3tom");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
//! Common error type.
|
||||
use thiserror::Error;
|
||||
|
||||
/// Errors produced by the core library.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum CoreError {
|
||||
#[error("I/O error: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("protocol error: {0}")]
|
||||
Proto(String),
|
||||
#[error("zone file error: {0}")]
|
||||
ZoneFile(String),
|
||||
#[error("timeout after {0:?}")]
|
||||
Timeout(std::time::Duration),
|
||||
#[error("TSIG error: {0}")]
|
||||
Tsig(String),
|
||||
#[error("response mismatch: {0}")]
|
||||
Mismatch(String),
|
||||
#[error("transfer error: {0}")]
|
||||
Transfer(String),
|
||||
#[error("invalid input: {0}")]
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
impl From<hickory_proto::ProtoError> for CoreError {
|
||||
fn from(e: hickory_proto::ProtoError) -> Self {
|
||||
CoreError::Proto(e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Result alias.
|
||||
pub type CoreResult<T> = Result<T, CoreError>;
|
||||
@@ -0,0 +1,54 @@
|
||||
//! EasyDNS core library.
|
||||
//!
|
||||
//! Shared protocol primitives used by every EasyDNS crate:
|
||||
//! * re-export of [`hickory_proto`] (wire format, record types, DNSSEC primitives),
|
||||
//! * RFC 1982 serial number arithmetic ([`serial`]),
|
||||
//! * BIND-style zone file parsing and emitting ([`zonefile`]),
|
||||
//! * TSIG (RFC 8945) signing and verification helpers ([`tsig`]),
|
||||
//! * an async DNS client with UDP→TCP fallback and zone-transfer streaming ([`client`]),
|
||||
//! * name normalisation helpers ([`names`]) and wire helpers ([`wire`]).
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
|
||||
|
||||
pub use hickory_proto as proto;
|
||||
|
||||
pub mod client;
|
||||
pub mod error;
|
||||
pub mod names;
|
||||
pub mod serial;
|
||||
pub mod tsig;
|
||||
pub mod wire;
|
||||
pub mod zonefile;
|
||||
pub mod zonefile_ext;
|
||||
|
||||
pub use error::{CoreError, CoreResult};
|
||||
|
||||
/// Commonly used re-exports.
|
||||
pub mod prelude {
|
||||
pub use hickory_proto::op::{Edns, Message, MessageType, OpCode, Query, ResponseCode};
|
||||
pub use hickory_proto::rr::{DNSClass, LowerName, Name, RData, Record, RecordType};
|
||||
}
|
||||
|
||||
pub mod answer;
|
||||
pub mod dnssec;
|
||||
pub mod tls;
|
||||
pub mod tls_pool;
|
||||
|
||||
/// Make command-line programs behave like classic Unix tools when their output pipe is
|
||||
/// closed early (`easydns … | head`): exit quietly with status 141 (128 + SIGPIPE)
|
||||
/// instead of printing a panic. Safe Rust cannot restore the default SIGPIPE action, so
|
||||
/// the panic raised by `println!` on EPIPE is recognised in a panic hook.
|
||||
pub fn quiet_broken_pipe() {
|
||||
let default = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
let msg = info
|
||||
.payload()
|
||||
.downcast_ref::<String>()
|
||||
.map(String::as_str)
|
||||
.or_else(|| info.payload().downcast_ref::<&str>().copied())
|
||||
.unwrap_or("");
|
||||
if msg.contains("Broken pipe") || msg.contains("os error 32") {
|
||||
std::process::exit(141);
|
||||
}
|
||||
default(info);
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
//! Name normalisation, validation and IDNA helpers.
|
||||
use hickory_proto::rr::{LowerName, Name};
|
||||
|
||||
use crate::{CoreError, CoreResult};
|
||||
|
||||
/// Parse a user-supplied domain name (ASCII or Unicode/IDN), returning a
|
||||
/// fully-qualified, lower-cased name.
|
||||
pub fn parse_name(input: &str) -> CoreResult<Name> {
|
||||
let s = input.trim();
|
||||
if s.is_empty() {
|
||||
return Err(CoreError::Invalid("empty domain name".into()));
|
||||
}
|
||||
let mut name = if s.is_ascii() { Name::from_ascii(s) } else { Name::from_utf8(s) }
|
||||
.map_err(|e| CoreError::Invalid(format!("invalid domain name '{s}': {e}")))?;
|
||||
name.set_fqdn(true);
|
||||
Ok(name.to_lowercase())
|
||||
}
|
||||
|
||||
/// Parse a name and return its [`LowerName`].
|
||||
pub fn parse_lower(input: &str) -> CoreResult<LowerName> {
|
||||
Ok(LowerName::new(&parse_name(input)?))
|
||||
}
|
||||
|
||||
/// Iterate over `name` and all of its ancestors, most specific first
|
||||
/// (`a.b.c.` → `a.b.c.`, `b.c.`, `c.`, `.`).
|
||||
pub fn ancestors(name: &Name) -> impl Iterator<Item = Name> + '_ {
|
||||
let n = name.num_labels() as usize;
|
||||
(0..=n).map(move |i| name.trim_to(n - i))
|
||||
}
|
||||
|
||||
/// Build the reverse-lookup name for an IP address (in-addr.arpa / ip6.arpa).
|
||||
pub fn reverse_name(ip: std::net::IpAddr) -> Name {
|
||||
Name::from(ip)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_and_idn() {
|
||||
assert_eq!(parse_name("Example.COM").unwrap().to_string(), "example.com.");
|
||||
assert_eq!(parse_name("zażółć.pl").unwrap().to_ascii(), "xn--za-6ja4f8n1l.pl.");
|
||||
assert!(parse_name("").is_err());
|
||||
assert!(parse_name("a..b").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ancestor_walk() {
|
||||
let n = parse_name("a.b.c").unwrap();
|
||||
let v: Vec<String> = ancestors(&n).map(|n| n.to_string()).collect();
|
||||
assert_eq!(v, vec!["a.b.c.", "b.c.", "c.", "."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse() {
|
||||
let n = reverse_name("192.0.2.1".parse().unwrap());
|
||||
assert_eq!(n.to_string(), "1.2.0.192.in-addr.arpa.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
//! RFC 1982 serial number arithmetic (32-bit SOA serials).
|
||||
use std::cmp::Ordering;
|
||||
|
||||
/// Compare two SOA serials according to RFC 1982.
|
||||
///
|
||||
/// Returns `None` when the comparison is undefined (the values are exactly
|
||||
/// 2^31 apart), in which case callers must treat the serials as incomparable.
|
||||
pub fn compare(a: u32, b: u32) -> Option<Ordering> {
|
||||
if a == b {
|
||||
return Some(Ordering::Equal);
|
||||
}
|
||||
let diff = b.wrapping_sub(a);
|
||||
if diff == 1 << 31 {
|
||||
return None;
|
||||
}
|
||||
if diff < (1 << 31) { Some(Ordering::Less) } else { Some(Ordering::Greater) }
|
||||
}
|
||||
|
||||
/// `true` when `new` is strictly newer than `old` (RFC 1982).
|
||||
pub fn is_newer(new: u32, old: u32) -> bool {
|
||||
compare(new, old) == Some(Ordering::Greater)
|
||||
}
|
||||
|
||||
/// Serial number generation strategy used when a primary zone changes.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum SerialStrategy {
|
||||
/// serial + 1
|
||||
#[default]
|
||||
Increment,
|
||||
/// UNIX time in seconds (never decreases below serial + 1)
|
||||
Unixtime,
|
||||
/// YYYYMMDDnn
|
||||
Date,
|
||||
}
|
||||
|
||||
/// Compute the next serial for `current` using `strategy`; `now_unix` is the
|
||||
/// current UNIX time. The result is always RFC 1982-newer than `current`.
|
||||
pub fn next_serial(current: u32, strategy: SerialStrategy, now_unix: u64) -> u32 {
|
||||
let candidate = match strategy {
|
||||
SerialStrategy::Increment => current.wrapping_add(1),
|
||||
SerialStrategy::Unixtime => now_unix as u32,
|
||||
SerialStrategy::Date => {
|
||||
let days = now_unix / 86_400;
|
||||
let (y, m, d) = civil_from_days(days as i64);
|
||||
let base = (y as u32) * 1_000_000 + m * 10_000 + d * 100;
|
||||
let cur_base = current - current % 100;
|
||||
if cur_base == base && current % 100 < 99 { current + 1 } else { base }
|
||||
}
|
||||
};
|
||||
if is_newer(candidate, current) { candidate } else { current.wrapping_add(1) }
|
||||
}
|
||||
|
||||
/// Convert days since 1970-01-01 into (year, month, day). (H. Hinnant's algorithm)
|
||||
fn civil_from_days(z: i64) -> (i64, u32, u32) {
|
||||
let z = z + 719_468;
|
||||
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
|
||||
let doe = (z - era * 146_097) as u64;
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let y = yoe as i64 + era * 400;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
|
||||
(if m <= 2 { y + 1 } else { y }, m, d)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rfc1982_basic() {
|
||||
assert_eq!(compare(1, 2), Some(Ordering::Less));
|
||||
assert_eq!(compare(2, 1), Some(Ordering::Greater));
|
||||
assert_eq!(compare(5, 5), Some(Ordering::Equal));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rfc1982_wrap() {
|
||||
assert!(is_newer(0, u32::MAX));
|
||||
assert!(is_newer(10, 4_294_967_290));
|
||||
assert!(!is_newer(4_294_967_290, 10));
|
||||
assert_eq!(compare(0, 1 << 31), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_serial_strategies() {
|
||||
assert_eq!(next_serial(41, SerialStrategy::Increment, 0), 42);
|
||||
assert_eq!(next_serial(u32::MAX, SerialStrategy::Increment, 0), 0);
|
||||
// 2026-11-21 00:00:00 UTC
|
||||
let t = 1_795_219_200;
|
||||
assert_eq!(next_serial(1, SerialStrategy::Date, t), 2026112100);
|
||||
assert_eq!(next_serial(2026112100, SerialStrategy::Date, t), 2026112101);
|
||||
assert_eq!(next_serial(5, SerialStrategy::Unixtime, t), t as u32);
|
||||
// unixtime never goes backwards
|
||||
assert_eq!(next_serial(t as u32 + 10, SerialStrategy::Unixtime, t), t as u32 + 11);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
//! DNS-over-TLS (RFC 7858) and DNS-over-HTTPS (RFC 8484) client transports on rustls.
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use data_encoding::BASE64URL_NOPAD;
|
||||
use rustls::pki_types::ServerName;
|
||||
use rustls::{ClientConfig, RootCertStore};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio_rustls::TlsConnector;
|
||||
|
||||
use crate::client::{read_tcp_msg, write_tcp_msg};
|
||||
use crate::{CoreError, CoreResult};
|
||||
|
||||
/// Maximum DoH response body we accept.
|
||||
pub const MAX_DOH_BODY: usize = 65_535;
|
||||
|
||||
/// Details of the TLS session, for diagnostics tools.
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct TlsInfo {
|
||||
pub protocol: String,
|
||||
pub cipher_suite: String,
|
||||
pub alpn: Option<String>,
|
||||
pub connect_ms: f64,
|
||||
pub handshake_ms: f64,
|
||||
pub peer_certificates: usize,
|
||||
}
|
||||
|
||||
/// Build a rustls client config with the Mozilla root store (webpki-roots), plus optional
|
||||
/// extra PEM roots. `insecure` disables certificate verification (diagnostics only).
|
||||
pub fn client_config(extra_roots_pem: Option<&[u8]>, insecure: bool, alpn: &[&[u8]]) -> CoreResult<Arc<ClientConfig>> {
|
||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||
let builder = ClientConfig::builder_with_provider(provider.clone())
|
||||
.with_safe_default_protocol_versions()
|
||||
.map_err(|e| CoreError::Invalid(e.to_string()))?;
|
||||
let mut cfg = if insecure {
|
||||
builder.dangerous().with_custom_certificate_verifier(Arc::new(NoVerify(provider))).with_no_client_auth()
|
||||
} else {
|
||||
let mut roots = RootCertStore::empty();
|
||||
roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
|
||||
if let Some(pem) = extra_roots_pem {
|
||||
use rustls::pki_types::{CertificateDer, pem::PemObject};
|
||||
for c in CertificateDer::pem_slice_iter(pem) {
|
||||
let c = c.map_err(|e| CoreError::Invalid(format!("bad CA PEM: {e}")))?;
|
||||
roots.add(c).map_err(|e| CoreError::Invalid(format!("bad CA cert: {e}")))?;
|
||||
}
|
||||
}
|
||||
builder.with_root_certificates(roots).with_no_client_auth()
|
||||
};
|
||||
cfg.alpn_protocols = alpn.iter().map(|a| a.to_vec()).collect();
|
||||
Ok(Arc::new(cfg))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct NoVerify(Arc<rustls::crypto::CryptoProvider>);
|
||||
|
||||
impl rustls::client::danger::ServerCertVerifier for NoVerify {
|
||||
fn verify_server_cert(
|
||||
&self,
|
||||
_: &rustls::pki_types::CertificateDer<'_>,
|
||||
_: &[rustls::pki_types::CertificateDer<'_>],
|
||||
_: &ServerName<'_>,
|
||||
_: &[u8],
|
||||
_: rustls::pki_types::UnixTime,
|
||||
) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
|
||||
Ok(rustls::client::danger::ServerCertVerified::assertion())
|
||||
}
|
||||
fn verify_tls12_signature(
|
||||
&self,
|
||||
m: &[u8],
|
||||
c: &rustls::pki_types::CertificateDer<'_>,
|
||||
d: &rustls::DigitallySignedStruct,
|
||||
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
|
||||
rustls::crypto::verify_tls12_signature(m, c, d, &self.0.signature_verification_algorithms)
|
||||
}
|
||||
fn verify_tls13_signature(
|
||||
&self,
|
||||
m: &[u8],
|
||||
c: &rustls::pki_types::CertificateDer<'_>,
|
||||
d: &rustls::DigitallySignedStruct,
|
||||
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
|
||||
rustls::crypto::verify_tls13_signature(m, c, d, &self.0.signature_verification_algorithms)
|
||||
}
|
||||
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
|
||||
self.0.signature_verification_algorithms.supported_schemes()
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect_tls(
|
||||
addr: SocketAddr,
|
||||
server_name: &str,
|
||||
cfg: Arc<ClientConfig>,
|
||||
) -> CoreResult<(tokio_rustls::client::TlsStream<TcpStream>, f64, f64)> {
|
||||
let t0 = Instant::now();
|
||||
let tcp = TcpStream::connect(addr).await?;
|
||||
tcp.set_nodelay(true)?;
|
||||
let connect_ms = t0.elapsed().as_secs_f64() * 1000.0;
|
||||
let name = ServerName::try_from(server_name.to_string())
|
||||
.map_err(|e| CoreError::Invalid(format!("invalid TLS server name '{server_name}': {e}")))?;
|
||||
let t1 = Instant::now();
|
||||
let tls =
|
||||
TlsConnector::from(cfg).connect(name, tcp).await.map_err(|e| CoreError::Proto(format!("TLS handshake with {addr} failed: {e}")))?;
|
||||
Ok((tls, connect_ms, t1.elapsed().as_secs_f64() * 1000.0))
|
||||
}
|
||||
|
||||
/// Open a TLS connection (TCP_NODELAY set), without timing details.
|
||||
pub async fn connect_tls_stream(
|
||||
addr: SocketAddr,
|
||||
server_name: &str,
|
||||
cfg: Arc<ClientConfig>,
|
||||
) -> CoreResult<tokio_rustls::client::TlsStream<TcpStream>> {
|
||||
connect_tls(addr, server_name, cfg).await.map(|(s, _, _)| s)
|
||||
}
|
||||
|
||||
fn info(s: &tokio_rustls::client::TlsStream<TcpStream>, connect_ms: f64, handshake_ms: f64) -> TlsInfo {
|
||||
let (_, c) = s.get_ref();
|
||||
TlsInfo {
|
||||
protocol: c.protocol_version().map(|v| format!("{v:?}")).unwrap_or_default(),
|
||||
cipher_suite: c.negotiated_cipher_suite().map(|s| format!("{:?}", s.suite())).unwrap_or_default(),
|
||||
alpn: c.alpn_protocol().map(|a| String::from_utf8_lossy(a).to_string()),
|
||||
connect_ms,
|
||||
handshake_ms,
|
||||
peer_certificates: c.peer_certificates().map(|p| p.len()).unwrap_or(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// One DoT exchange. Returns the raw response and TLS details.
|
||||
pub async fn dot_exchange(
|
||||
addr: SocketAddr,
|
||||
server_name: &str,
|
||||
query: &[u8],
|
||||
timeout: Duration,
|
||||
cfg: Arc<ClientConfig>,
|
||||
) -> CoreResult<(Vec<u8>, TlsInfo)> {
|
||||
let fut = async {
|
||||
let (mut s, c, h) = connect_tls(addr, server_name, cfg).await?;
|
||||
write_tcp_msg(&mut s, query).await?;
|
||||
let raw = read_tcp_msg(&mut s).await?;
|
||||
let i = info(&s, c, h);
|
||||
let _ = s.shutdown().await;
|
||||
Ok((raw, i))
|
||||
};
|
||||
tokio::time::timeout(timeout, fut).await.map_err(|_| CoreError::Timeout(timeout))?
|
||||
}
|
||||
|
||||
/// HTTP method used for DoH.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DohMethod {
|
||||
Get,
|
||||
Post,
|
||||
}
|
||||
|
||||
/// One DoH exchange over HTTP/1.1. Returns (status, raw body, TLS info).
|
||||
pub async fn doh_exchange(
|
||||
addr: SocketAddr,
|
||||
server_name: &str,
|
||||
path: &str,
|
||||
query: &[u8],
|
||||
method: DohMethod,
|
||||
timeout: Duration,
|
||||
cfg: Arc<ClientConfig>,
|
||||
) -> CoreResult<(u16, Vec<u8>, TlsInfo)> {
|
||||
let fut = async {
|
||||
let (mut s, c, h) = connect_tls(addr, server_name, cfg).await?;
|
||||
let req = match method {
|
||||
DohMethod::Post => {
|
||||
let mut r = format!(
|
||||
"POST {path} HTTP/1.1\r\nHost: {server_name}\r\nUser-Agent: EasyDNS\r\nContent-Type: application/dns-message\r\nAccept: application/dns-message\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
||||
query.len()
|
||||
)
|
||||
.into_bytes();
|
||||
r.extend_from_slice(query);
|
||||
r
|
||||
}
|
||||
DohMethod::Get => {
|
||||
// RFC 8484 §4.1: use ID 0 for cache friendliness.
|
||||
let mut q = query.to_vec();
|
||||
if q.len() >= 2 {
|
||||
q[0] = 0;
|
||||
q[1] = 0;
|
||||
}
|
||||
let sep = if path.contains('?') { '&' } else { '?' };
|
||||
format!(
|
||||
"GET {path}{sep}dns={} HTTP/1.1\r\nHost: {server_name}\r\nUser-Agent: EasyDNS\r\nAccept: application/dns-message\r\nConnection: close\r\n\r\n",
|
||||
BASE64URL_NOPAD.encode(&q)
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
};
|
||||
s.write_all(&req).await?;
|
||||
s.flush().await?;
|
||||
let i = info(&s, c, h);
|
||||
let mut buf = Vec::new();
|
||||
let mut chunk = [0u8; 8192];
|
||||
loop {
|
||||
let n = match s.read(&mut chunk).await {
|
||||
Ok(0) => break,
|
||||
Ok(n) => n,
|
||||
// Many servers close without close_notify after `Connection: close`.
|
||||
Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
buf.extend_from_slice(&chunk[..n]);
|
||||
if buf.len() > MAX_DOH_BODY + 16_384 {
|
||||
return Err(CoreError::Proto("DoH response too large".into()));
|
||||
}
|
||||
if let Some((status, body)) = parse_http_response(&buf)? {
|
||||
return Ok((status, body, i));
|
||||
}
|
||||
}
|
||||
match parse_http_response(&buf)? {
|
||||
Some((status, body)) => Ok((status, body, i)),
|
||||
None => Err(CoreError::Proto("incomplete HTTP response".into())),
|
||||
}
|
||||
};
|
||||
tokio::time::timeout(timeout, fut).await.map_err(|_| CoreError::Timeout(timeout))?
|
||||
}
|
||||
|
||||
/// Parse a complete HTTP/1.1 response (Content-Length or chunked). `Ok(None)` = need more data.
|
||||
pub fn parse_http_response(buf: &[u8]) -> CoreResult<Option<(u16, Vec<u8>)>> {
|
||||
parse_http_response_limited(buf, MAX_DOH_BODY)
|
||||
}
|
||||
|
||||
/// Like [`parse_http_response`] with a custom body limit.
|
||||
pub fn parse_http_response_limited(buf: &[u8], max_body: usize) -> CoreResult<Option<(u16, Vec<u8>)>> {
|
||||
let Some(hdr_end) = buf.windows(4).position(|w| w == b"\r\n\r\n") else {
|
||||
return Ok(None);
|
||||
};
|
||||
let head = std::str::from_utf8(&buf[..hdr_end]).map_err(|_| CoreError::Proto("non-UTF8 HTTP headers".into()))?;
|
||||
let mut lines = head.split("\r\n");
|
||||
let status_line = lines.next().unwrap_or("");
|
||||
let status: u16 = status_line
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.and_then(|s| s.parse().ok())
|
||||
.ok_or_else(|| CoreError::Proto(format!("bad HTTP status line '{status_line}'")))?;
|
||||
let mut clen: Option<usize> = None;
|
||||
let mut chunked = false;
|
||||
for l in lines {
|
||||
if let Some((k, v)) = l.split_once(':') {
|
||||
let k = k.trim().to_ascii_lowercase();
|
||||
let v = v.trim();
|
||||
if k == "content-length" {
|
||||
clen = v.parse().ok();
|
||||
} else if k == "transfer-encoding" && v.to_ascii_lowercase().contains("chunked") {
|
||||
chunked = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let body = &buf[hdr_end + 4..];
|
||||
if chunked {
|
||||
let mut out = Vec::new();
|
||||
let mut rest = body;
|
||||
loop {
|
||||
let Some(le) = rest.windows(2).position(|w| w == b"\r\n") else { return Ok(None) };
|
||||
let size_str = std::str::from_utf8(&rest[..le]).unwrap_or("").split(';').next().unwrap_or("").trim();
|
||||
let size = usize::from_str_radix(size_str, 16).map_err(|_| CoreError::Proto("bad chunk size".into()))?;
|
||||
if size == 0 {
|
||||
return Ok(Some((status, out)));
|
||||
}
|
||||
if rest.len() < le + 2 + size + 2 {
|
||||
return Ok(None);
|
||||
}
|
||||
out.extend_from_slice(&rest[le + 2..le + 2 + size]);
|
||||
if out.len() > max_body {
|
||||
return Err(CoreError::Proto("HTTP body too large".into()));
|
||||
}
|
||||
rest = &rest[le + 2 + size + 2..];
|
||||
}
|
||||
}
|
||||
match clen {
|
||||
Some(n) if n > max_body => Err(CoreError::Proto("HTTP body too large".into())),
|
||||
Some(n) if body.len() >= n => Ok(Some((status, body[..n].to_vec()))),
|
||||
Some(_) => Ok(None),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal HTTPS GET (HTTP/1.1, system resolver, webpki roots). Used for block lists,
|
||||
/// root hints updates and RDAP. Returns (status, body).
|
||||
pub async fn https_get(url: &str, timeout: Duration, max_body: usize) -> CoreResult<(u16, Vec<u8>)> {
|
||||
let rest = url.strip_prefix("https://").ok_or_else(|| CoreError::Invalid("only https:// URLs are supported".into()))?;
|
||||
let (hostport, path) = match rest.find('/') {
|
||||
Some(i) => (&rest[..i], &rest[i..]),
|
||||
None => (rest, "/"),
|
||||
};
|
||||
let (host, port) = match hostport.rsplit_once(':') {
|
||||
Some((h, p)) if !h.contains(']') || h.ends_with(']') => (h.trim_matches(['[', ']']), p.parse().unwrap_or(443)),
|
||||
_ => (hostport, 443u16),
|
||||
};
|
||||
let fut = async {
|
||||
let addr =
|
||||
tokio::net::lookup_host((host, port)).await?.next().ok_or_else(|| CoreError::Invalid(format!("cannot resolve {host}")))?;
|
||||
let cfg = client_config(None, false, &[b"http/1.1"])?;
|
||||
let (mut s, _, _) = connect_tls(addr, host, cfg).await?;
|
||||
let req = format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: EasyDNS\r\nAccept: */*\r\nConnection: close\r\n\r\n");
|
||||
s.write_all(req.as_bytes()).await?;
|
||||
let mut buf = Vec::new();
|
||||
let mut chunk = [0u8; 16384];
|
||||
loop {
|
||||
let n = match s.read(&mut chunk).await {
|
||||
Ok(0) => break,
|
||||
Ok(n) => n,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
buf.extend_from_slice(&chunk[..n]);
|
||||
if buf.len() > max_body + 65_536 {
|
||||
return Err(CoreError::Proto("HTTP response too large".into()));
|
||||
}
|
||||
}
|
||||
match parse_http_response_limited(&buf, max_body)? {
|
||||
Some(r) => Ok(r),
|
||||
None => {
|
||||
// Connection: close without Content-Length: body is the rest of the stream.
|
||||
let p = buf.windows(4).position(|w| w == b"\r\n\r\n").ok_or_else(|| CoreError::Proto("incomplete HTTP response".into()))?;
|
||||
let status =
|
||||
std::str::from_utf8(&buf[..p]).ok().and_then(|h| h.split_whitespace().nth(1)).and_then(|s| s.parse().ok()).unwrap_or(0);
|
||||
Ok((status, buf[p + 4..].to_vec()))
|
||||
}
|
||||
}
|
||||
};
|
||||
tokio::time::timeout(timeout, fut).await.map_err(|_| CoreError::Timeout(timeout))?
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn http_parsing() {
|
||||
let r = b"HTTP/1.1 200 OK\r\nContent-Type: application/dns-message\r\nContent-Length: 3\r\n\r\nabc";
|
||||
assert_eq!(parse_http_response(r).unwrap(), Some((200, b"abc".to_vec())));
|
||||
assert_eq!(parse_http_response(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nab").unwrap(), None);
|
||||
let c = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n2\r\nde\r\n0\r\n\r\n";
|
||||
assert_eq!(parse_http_response(c).unwrap(), Some((200, b"abcde".to_vec())));
|
||||
assert!(parse_http_response(b"garbage\r\n\r\n").is_err());
|
||||
}
|
||||
#[test]
|
||||
fn config_builds() {
|
||||
assert!(client_config(None, false, &[b"h2"]).is_ok());
|
||||
assert!(client_config(None, true, &[]).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
//! Persistent encrypted upstream connections for the forwarder.
|
||||
//!
|
||||
//! Opening a TLS connection costs one TCP and one TLS round trip plus the handshake CPU;
|
||||
//! doing it per query (as the one-shot helpers in [`crate::tls`] do) makes encrypted
|
||||
//! forwarding several times slower than plain DNS. These clients keep connections open:
|
||||
//!
|
||||
//! * [`DotPool`] – DNS-over-TLS (RFC 7858): a small pool of idle connections, each used
|
||||
//! for one query at a time (RFC 7766 framing), reused while the server keeps it open.
|
||||
//! * [`DohClient`] – DNS-over-HTTPS (RFC 8484) over **HTTP/2**: one multiplexed
|
||||
//! connection carries all concurrent queries; falls back to HTTP/1.1 when the server
|
||||
//! does not offer `h2` in ALPN.
|
||||
//!
|
||||
//! A reused connection that turns out to be closed is retried once on a fresh one.
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
use http_body_util::{BodyExt, Full, Limited};
|
||||
use hyper::client::conn::http2;
|
||||
use hyper_util::rt::{TokioExecutor, TokioIo};
|
||||
use rustls::ClientConfig;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio_rustls::client::TlsStream;
|
||||
|
||||
use crate::client::{read_tcp_msg, write_tcp_msg};
|
||||
use crate::tls::{DohMethod, connect_tls_stream, doh_exchange};
|
||||
use crate::{CoreError, CoreResult};
|
||||
|
||||
/// Idle connections older than this are not reused (servers close idle DoT after ~10–30 s).
|
||||
const MAX_IDLE: Duration = Duration::from_secs(20);
|
||||
/// Largest accepted DoH response body.
|
||||
const MAX_BODY: usize = 65_535;
|
||||
|
||||
fn with_alpn(base: &Arc<ClientConfig>, alpn: &[&[u8]]) -> Arc<ClientConfig> {
|
||||
let mut c = (**base).clone();
|
||||
c.alpn_protocols = alpn.iter().map(|a| a.to_vec()).collect();
|
||||
Arc::new(c)
|
||||
}
|
||||
|
||||
/// Pool of DNS-over-TLS connections to one upstream.
|
||||
pub struct DotPool {
|
||||
addr: SocketAddr,
|
||||
name: String,
|
||||
cfg: Arc<ClientConfig>,
|
||||
idle: Mutex<Vec<(TlsStream<TcpStream>, Instant)>>,
|
||||
max_idle: usize,
|
||||
}
|
||||
|
||||
impl DotPool {
|
||||
pub fn new(addr: SocketAddr, tls_name: &str, base: &Arc<ClientConfig>, max_idle: usize) -> Self {
|
||||
Self { addr, name: tls_name.to_string(), cfg: with_alpn(base, &[b"dot"]), idle: Mutex::new(Vec::new()), max_idle: max_idle.max(1) }
|
||||
}
|
||||
|
||||
async fn checkout(&self) -> Option<TlsStream<TcpStream>> {
|
||||
let mut idle = self.idle.lock().await;
|
||||
while let Some((s, t)) = idle.pop() {
|
||||
if t.elapsed() < MAX_IDLE {
|
||||
return Some(s);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
async fn checkin(&self, s: TlsStream<TcpStream>) {
|
||||
let mut idle = self.idle.lock().await;
|
||||
if idle.len() < self.max_idle {
|
||||
idle.push((s, Instant::now()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of idle pooled connections (for tests and status).
|
||||
pub async fn idle_connections(&self) -> usize {
|
||||
self.idle.lock().await.len()
|
||||
}
|
||||
|
||||
/// Send one DNS message and return the raw response.
|
||||
pub async fn exchange(&self, query: &[u8], timeout: Duration) -> CoreResult<Vec<u8>> {
|
||||
let deadline = Instant::now() + timeout;
|
||||
for attempt in 0..2 {
|
||||
let (mut s, reused) = match self.checkout().await {
|
||||
Some(s) if attempt == 0 => (s, true),
|
||||
_ => (connect_tls_stream(self.addr, &self.name, Arc::clone(&self.cfg)).await?, false),
|
||||
};
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
let r = tokio::time::timeout(left, async {
|
||||
write_tcp_msg(&mut s, query).await?;
|
||||
read_tcp_msg(&mut s).await
|
||||
})
|
||||
.await;
|
||||
match r {
|
||||
Ok(Ok(raw)) => {
|
||||
self.checkin(s).await;
|
||||
return Ok(raw);
|
||||
}
|
||||
// the server closed an idle connection: try once more on a new one
|
||||
Ok(Err(_)) if reused => continue,
|
||||
Ok(Err(e)) => return Err(e),
|
||||
Err(_) => return Err(CoreError::Timeout(timeout)),
|
||||
}
|
||||
}
|
||||
Err(CoreError::Proto("DoT exchange failed".into()))
|
||||
}
|
||||
}
|
||||
|
||||
enum DohConn {
|
||||
H2(http2::SendRequest<Full<Bytes>>),
|
||||
/// Server did not negotiate h2: use one HTTP/1.1 exchange per query.
|
||||
Http1,
|
||||
}
|
||||
|
||||
/// DNS-over-HTTPS client for one upstream, multiplexing queries over HTTP/2.
|
||||
pub struct DohClient {
|
||||
addr: SocketAddr,
|
||||
name: String,
|
||||
path: String,
|
||||
cfg: Arc<ClientConfig>,
|
||||
h1_cfg: Arc<ClientConfig>,
|
||||
conn: Mutex<Option<http2::SendRequest<Full<Bytes>>>>,
|
||||
http1_only: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
|
||||
impl DohClient {
|
||||
pub fn new(addr: SocketAddr, tls_name: &str, path: &str, base: &Arc<ClientConfig>) -> Self {
|
||||
Self {
|
||||
addr,
|
||||
name: tls_name.to_string(),
|
||||
path: if path.is_empty() { "/dns-query".into() } else { path.to_string() },
|
||||
cfg: with_alpn(base, &[b"h2", b"http/1.1"]),
|
||||
h1_cfg: with_alpn(base, &[b"http/1.1"]),
|
||||
conn: Mutex::new(None),
|
||||
http1_only: std::sync::atomic::AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the last connection negotiated HTTP/2.
|
||||
pub fn uses_http2(&self) -> bool {
|
||||
!self.http1_only.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
async fn sender(&self, fresh: bool) -> CoreResult<DohConn> {
|
||||
if self.http1_only.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
return Ok(DohConn::Http1);
|
||||
}
|
||||
let mut slot = self.conn.lock().await;
|
||||
if !fresh {
|
||||
if let Some(s) = slot.as_ref().filter(|s| !s.is_closed()) {
|
||||
return Ok(DohConn::H2(s.clone()));
|
||||
}
|
||||
}
|
||||
let tls = connect_tls_stream(self.addr, &self.name, Arc::clone(&self.cfg)).await?;
|
||||
if tls.get_ref().1.alpn_protocol() != Some(b"h2") {
|
||||
self.http1_only.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
return Ok(DohConn::Http1);
|
||||
}
|
||||
let (send, conn) = http2::Builder::new(TokioExecutor::new())
|
||||
.handshake(TokioIo::new(tls))
|
||||
.await
|
||||
.map_err(|e| CoreError::Proto(format!("HTTP/2 handshake with {} failed: {e}", self.addr)))?;
|
||||
let addr = self.addr;
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = conn.await {
|
||||
tracing::debug!(%addr, error = %e, "DoH HTTP/2 connection closed");
|
||||
}
|
||||
});
|
||||
*slot = Some(send.clone());
|
||||
Ok(DohConn::H2(send))
|
||||
}
|
||||
|
||||
async fn h2_request(&self, mut send: http2::SendRequest<Full<Bytes>>, query: &[u8], method: DohMethod) -> CoreResult<(u16, Vec<u8>)> {
|
||||
let base = format!("https://{}{}", self.name, self.path);
|
||||
let req = match method {
|
||||
DohMethod::Post => hyper::Request::post(base)
|
||||
.header("content-type", "application/dns-message")
|
||||
.header("accept", "application/dns-message")
|
||||
.body(Full::new(Bytes::copy_from_slice(query))),
|
||||
DohMethod::Get => {
|
||||
let mut q = query.to_vec();
|
||||
if q.len() >= 2 {
|
||||
q[0] = 0;
|
||||
q[1] = 0; // RFC 8484 §4.1: ID 0 for cache friendliness
|
||||
}
|
||||
let sep = if base.contains('?') { '&' } else { '?' };
|
||||
hyper::Request::get(format!("{base}{sep}dns={}", data_encoding::BASE64URL_NOPAD.encode(&q)))
|
||||
.header("accept", "application/dns-message")
|
||||
.body(Full::new(Bytes::new()))
|
||||
}
|
||||
}
|
||||
.map_err(|e| CoreError::Invalid(e.to_string()))?;
|
||||
send.ready().await.map_err(|e| CoreError::Proto(format!("DoH connection: {e}")))?;
|
||||
let resp = send.send_request(req).await.map_err(|e| CoreError::Proto(format!("DoH request: {e}")))?;
|
||||
let status = resp.status().as_u16();
|
||||
let body = Limited::new(resp.into_body(), MAX_BODY)
|
||||
.collect()
|
||||
.await
|
||||
.map_err(|e| CoreError::Proto(format!("DoH response body: {e}")))?
|
||||
.to_bytes();
|
||||
Ok((status, body.to_vec()))
|
||||
}
|
||||
|
||||
/// One DoH exchange: (HTTP status, body).
|
||||
pub async fn exchange(&self, query: &[u8], method: DohMethod, timeout: Duration) -> CoreResult<(u16, Vec<u8>)> {
|
||||
let fut = async {
|
||||
for attempt in 0..2 {
|
||||
match self.sender(attempt > 0).await? {
|
||||
DohConn::Http1 => {
|
||||
let (st, body, _) =
|
||||
doh_exchange(self.addr, &self.name, &self.path, query, method, timeout, Arc::clone(&self.h1_cfg)).await?;
|
||||
return Ok((st, body));
|
||||
}
|
||||
DohConn::H2(send) => match self.h2_request(send, query, method).await {
|
||||
Ok(r) => return Ok(r),
|
||||
Err(e) if attempt == 0 => tracing::debug!(error = %e, "DoH: retrying on a new connection"),
|
||||
Err(e) => return Err(e),
|
||||
},
|
||||
}
|
||||
}
|
||||
Err(CoreError::Proto("DoH exchange failed".into()))
|
||||
};
|
||||
tokio::time::timeout(timeout, fut).await.map_err(|_| CoreError::Timeout(timeout))?
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for DotPool {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("DotPool").field("addr", &self.addr).field("name", &self.name).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for DohClient {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("DohClient").field("addr", &self.addr).field("name", &self.name).field("path", &self.path).finish()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
//! TSIG (RFC 8945) helpers built on hickory-proto's HMAC primitives.
|
||||
//!
|
||||
//! * [`TsigKey::sign_request`] – client side request signing.
|
||||
//! * [`verify_request`] – server side verification of a signed request.
|
||||
//! * [`ResponseSigner`] – server side signing of (multi-message) responses.
|
||||
//! * [`ResponseVerifier`] – client side verification of (multi-message) responses,
|
||||
//! including the RFC 8945 §5.3.1 rule that intermediate messages may be unsigned.
|
||||
use std::collections::HashMap;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use data_encoding::BASE64;
|
||||
use hickory_proto::op::Message;
|
||||
use hickory_proto::rr::rdata::tsig::{TSIG, TsigAlgorithm, make_tsig_record, signed_bitmessage_to_buf};
|
||||
use hickory_proto::rr::{Name, TSigner};
|
||||
use hickory_proto::serialize::binary::BinEncoder;
|
||||
|
||||
use crate::{CoreError, CoreResult};
|
||||
|
||||
/// Default allowed clock skew in seconds.
|
||||
pub const DEFAULT_FUDGE: u16 = 300;
|
||||
/// RFC 8945 §5.3.1: at most 99 unsigned messages between signed ones.
|
||||
pub const MAX_UNSIGNED_RUN: usize = 99;
|
||||
|
||||
/// Current UNIX time in seconds.
|
||||
pub fn now() -> u64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// A named shared secret. The secret is never printed by `Debug`.
|
||||
#[derive(Clone)]
|
||||
pub struct TsigKey {
|
||||
pub name: Name,
|
||||
pub algorithm: TsigAlgorithm,
|
||||
secret: Vec<u8>,
|
||||
signer: TSigner,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for TsigKey {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("TsigKey")
|
||||
.field("name", &self.name.to_string())
|
||||
.field("algorithm", &self.algorithm.to_string())
|
||||
.field("secret", &"<redacted>")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse an algorithm name (`hmac-sha256`, `hmac-sha512`, ...).
|
||||
pub fn parse_algorithm(s: &str) -> CoreResult<TsigAlgorithm> {
|
||||
let n = Name::from_ascii(s.trim_end_matches('.')).map_err(|e| CoreError::Tsig(format!("bad algorithm {s}: {e}")))?;
|
||||
let alg = TsigAlgorithm::from_name(n);
|
||||
if !alg.supported() || matches!(alg, TsigAlgorithm::HmacMd5) {
|
||||
return Err(CoreError::Tsig(format!("unsupported TSIG algorithm '{s}'")));
|
||||
}
|
||||
Ok(alg)
|
||||
}
|
||||
|
||||
impl TsigKey {
|
||||
/// Build a key from its name, algorithm and base64 secret.
|
||||
pub fn new(name: &str, algorithm: &str, secret_b64: &str) -> CoreResult<Self> {
|
||||
let secret = BASE64
|
||||
.decode(secret_b64.trim().as_bytes())
|
||||
.map_err(|e| CoreError::Tsig(format!("key {name}: secret is not valid base64: {e}")))?;
|
||||
if secret.len() < 16 {
|
||||
return Err(CoreError::Tsig(format!("key {name}: secret too short (<128 bits)")));
|
||||
}
|
||||
let mut kname = crate::names::parse_name(name)?;
|
||||
kname.set_fqdn(true);
|
||||
let algorithm = parse_algorithm(algorithm)?;
|
||||
let signer =
|
||||
TSigner::new(secret.clone(), algorithm.clone(), kname.clone(), DEFAULT_FUDGE).map_err(|e| CoreError::Tsig(e.to_string()))?;
|
||||
Ok(Self { name: kname, algorithm, secret, signer })
|
||||
}
|
||||
|
||||
/// Secret length (for diagnostics only).
|
||||
pub fn secret_len(&self) -> usize {
|
||||
self.secret.len()
|
||||
}
|
||||
|
||||
fn mac(&self, tbs: &[u8]) -> CoreResult<Vec<u8>> {
|
||||
self.signer.sign(tbs).map_err(|e| CoreError::Tsig(e.to_string()))
|
||||
}
|
||||
|
||||
/// Sign a request in place; returns the request MAC (needed to verify the response).
|
||||
pub fn sign_request(&self, msg: &mut Message) -> CoreResult<Vec<u8>> {
|
||||
msg.signature = None;
|
||||
let (rec, _) = self.signer.sign_message(msg, now()).map_err(|e| CoreError::Tsig(e.to_string()))?;
|
||||
let mac = rec.data.mac.clone();
|
||||
msg.signature = Some(rec);
|
||||
Ok(mac)
|
||||
}
|
||||
}
|
||||
|
||||
/// Collection of keys indexed by (lower-case) key name.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct KeyRing {
|
||||
keys: HashMap<String, TsigKey>,
|
||||
}
|
||||
|
||||
impl KeyRing {
|
||||
pub fn insert(&mut self, key: TsigKey) {
|
||||
self.keys.insert(key.name.to_lowercase().to_string(), key);
|
||||
}
|
||||
pub fn get(&self, name: &Name) -> Option<&TsigKey> {
|
||||
self.keys.get(&name.to_lowercase().to_string())
|
||||
}
|
||||
pub fn get_str(&self, name: &str) -> Option<&TsigKey> {
|
||||
let n = crate::names::parse_name(name).ok()?;
|
||||
self.get(&n)
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.keys.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of checking a request's TSIG.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum TsigStatus {
|
||||
/// Request carries no TSIG.
|
||||
Unsigned,
|
||||
/// Valid signature by `key`; `mac` must be used when signing the response.
|
||||
Valid { key: TsigKey, mac: Vec<u8> },
|
||||
/// Signature present but invalid (unknown key, bad MAC, bad time).
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
/// Verify the TSIG (if any) of a raw request.
|
||||
pub fn verify_request(raw: &[u8], msg: &Message, ring: &KeyRing) -> TsigStatus {
|
||||
let Some(sig) = &msg.signature else {
|
||||
return TsigStatus::Unsigned;
|
||||
};
|
||||
let Some(key) = ring.get(&sig.name) else {
|
||||
return TsigStatus::Invalid(format!("unknown key {}", sig.name));
|
||||
};
|
||||
match key.signer.verify_message_byte(raw, None, true) {
|
||||
Ok((mac, _time, range)) => {
|
||||
let n = now();
|
||||
if range.contains(&n) || range.end == n {
|
||||
TsigStatus::Valid { key: key.clone(), mac }
|
||||
} else {
|
||||
TsigStatus::Invalid("signature time outside fudge window (BADTIME)".into())
|
||||
}
|
||||
}
|
||||
Err(e) => TsigStatus::Invalid(format!("bad signature: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Signs a sequence of response messages (e.g. an AXFR stream).
|
||||
pub struct ResponseSigner {
|
||||
key: TsigKey,
|
||||
prev_mac: Vec<u8>,
|
||||
first: bool,
|
||||
pending: Vec<u8>,
|
||||
}
|
||||
|
||||
impl ResponseSigner {
|
||||
pub fn new(key: TsigKey, request_mac: Vec<u8>) -> Self {
|
||||
Self { key, prev_mac: request_mac, first: true, pending: Vec::new() }
|
||||
}
|
||||
|
||||
/// Encode an intermediate message without a signature (RFC 8945 §5.3.1).
|
||||
/// The next signed message covers it.
|
||||
pub fn emit_unsigned(&mut self, msg: &mut Message) -> CoreResult<Vec<u8>> {
|
||||
if self.first {
|
||||
return Err(CoreError::Tsig("first message must be signed".into()));
|
||||
}
|
||||
msg.signature = None;
|
||||
let raw = msg.to_vec()?;
|
||||
self.pending.extend_from_slice(&raw);
|
||||
Ok(raw)
|
||||
}
|
||||
|
||||
/// Sign `msg` (which must not already carry a signature) and return the encoded bytes.
|
||||
pub fn sign(&mut self, msg: &mut Message) -> CoreResult<Vec<u8>> {
|
||||
msg.signature = None;
|
||||
let unsigned = msg.to_vec()?;
|
||||
let time = now();
|
||||
let stub = TSIG::new(self.key.algorithm.clone(), time, DEFAULT_FUDGE, Vec::new(), msg.metadata.id, None, Vec::new());
|
||||
let mut tbs = Vec::with_capacity(unsigned.len() + 128);
|
||||
{
|
||||
let mut enc = BinEncoder::new(&mut tbs);
|
||||
enc.emit_u16(self.prev_mac.len() as u16)?;
|
||||
enc.emit_vec(&self.prev_mac)?;
|
||||
enc.emit_vec(&self.pending)?;
|
||||
enc.emit_vec(&unsigned)?;
|
||||
if self.first {
|
||||
stub.emit_tsig_for_mac(&mut enc, &self.key.name)?;
|
||||
} else {
|
||||
enc.emit_u16((time >> 32) as u16)?;
|
||||
enc.emit_u32(time as u32)?;
|
||||
enc.emit_u16(DEFAULT_FUDGE)?;
|
||||
}
|
||||
}
|
||||
let mac = self.key.mac(&tbs)?;
|
||||
let rec = make_tsig_record(self.key.name.clone(), stub.set_mac(mac.clone()));
|
||||
msg.signature = Some(Box::new(rec));
|
||||
self.prev_mac = mac;
|
||||
self.first = false;
|
||||
self.pending.clear();
|
||||
Ok(msg.to_vec()?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Verifies a sequence of TSIG-signed response messages.
|
||||
pub struct ResponseVerifier {
|
||||
key: TsigKey,
|
||||
prev_mac: Vec<u8>,
|
||||
first: bool,
|
||||
unsigned: Vec<u8>,
|
||||
unsigned_run: usize,
|
||||
}
|
||||
|
||||
impl ResponseVerifier {
|
||||
pub fn new(key: TsigKey, request_mac: Vec<u8>) -> Self {
|
||||
Self { key, prev_mac: request_mac, first: true, unsigned: Vec::new(), unsigned_run: 0 }
|
||||
}
|
||||
|
||||
/// Feed the next raw message. Returns `Ok(true)` if it was signed and verified,
|
||||
/// `Ok(false)` if it was an allowed unsigned intermediate message.
|
||||
pub fn verify(&mut self, raw: &[u8], parsed: &Message) -> CoreResult<bool> {
|
||||
if parsed.signature.is_none() {
|
||||
if self.first {
|
||||
return Err(CoreError::Tsig("first response message is not signed".into()));
|
||||
}
|
||||
self.unsigned_run += 1;
|
||||
if self.unsigned_run > MAX_UNSIGNED_RUN {
|
||||
return Err(CoreError::Tsig("too many unsigned messages in a row".into()));
|
||||
}
|
||||
self.unsigned.extend_from_slice(raw);
|
||||
return Ok(false);
|
||||
}
|
||||
let (body, rec) = signed_bitmessage_to_buf(raw, None, self.first)?;
|
||||
if rec.name != self.key.name || rec.data.algorithm != self.key.algorithm {
|
||||
return Err(CoreError::Tsig("response signed with unexpected key".into()));
|
||||
}
|
||||
let mut tbs = Vec::with_capacity(body.len() + self.unsigned.len() + 64);
|
||||
tbs.extend_from_slice(&(self.prev_mac.len() as u16).to_be_bytes());
|
||||
tbs.extend_from_slice(&self.prev_mac);
|
||||
tbs.extend_from_slice(&self.unsigned);
|
||||
tbs.extend_from_slice(&body);
|
||||
self.key.signer.verify(&tbs, &rec.data.mac).map_err(|_| CoreError::Tsig("response MAC verification failed (BADSIG)".into()))?;
|
||||
let t = rec.data.time;
|
||||
let n = now();
|
||||
let fudge = u64::from(rec.data.fudge);
|
||||
if n + fudge < t || t + fudge < n {
|
||||
return Err(CoreError::Tsig("response time outside fudge window (BADTIME)".into()));
|
||||
}
|
||||
self.prev_mac = rec.data.mac.clone();
|
||||
self.first = false;
|
||||
self.unsigned.clear();
|
||||
self.unsigned_run = 0;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The last message of a stream must be signed.
|
||||
pub fn finish(&self) -> CoreResult<()> {
|
||||
if self.unsigned_run > 0 || self.first {
|
||||
return Err(CoreError::Tsig("last response message is not signed".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use hickory_proto::op::{Message, MessageType, OpCode, Query};
|
||||
use hickory_proto::rr::{RData, Record, RecordType, rdata::A};
|
||||
|
||||
fn key() -> TsigKey {
|
||||
TsigKey::new("xfr-key", "hmac-sha256", "c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0").unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_roundtrip_and_tamper() {
|
||||
let k = key();
|
||||
let mut ring = KeyRing::default();
|
||||
ring.insert(k.clone());
|
||||
let mut q = Message::query();
|
||||
q.add_query(Query::query(Name::from_ascii("example.com.").unwrap(), RecordType::AXFR));
|
||||
let mac = k.sign_request(&mut q).unwrap();
|
||||
let raw = q.to_vec().unwrap();
|
||||
let parsed = Message::from_vec(&raw).unwrap();
|
||||
match verify_request(&raw, &parsed, &ring) {
|
||||
TsigStatus::Valid { mac: m, .. } => assert_eq!(m, mac),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
let mut bad = raw.clone();
|
||||
bad[13] ^= 0x20; // flip case of a question byte -> MAC invalid
|
||||
let parsed = Message::from_vec(&bad).unwrap();
|
||||
assert!(matches!(verify_request(&bad, &parsed, &ring), TsigStatus::Invalid(_)));
|
||||
let other = KeyRing::default();
|
||||
let parsed = Message::from_vec(&raw).unwrap();
|
||||
assert!(matches!(verify_request(&raw, &parsed, &other), TsigStatus::Invalid(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_message_chain() {
|
||||
let k = key();
|
||||
let mut q = Message::query();
|
||||
q.add_query(Query::query(Name::from_ascii("example.com.").unwrap(), RecordType::AXFR));
|
||||
let mac = k.sign_request(&mut q).unwrap();
|
||||
let mut signer = ResponseSigner::new(k.clone(), mac.clone());
|
||||
let mut verifier = ResponseVerifier::new(k.clone(), mac);
|
||||
for i in 0..3u8 {
|
||||
let mut m = Message::new(q.metadata.id, MessageType::Response, OpCode::Query);
|
||||
m.add_answer(Record::from_rdata(Name::from_ascii("a.example.com.").unwrap(), 60, RData::A(A::new(192, 0, 2, i))));
|
||||
let raw = if i == 1 { signer.emit_unsigned(&mut m).unwrap() } else { signer.sign(&mut m).unwrap() };
|
||||
let parsed = Message::from_vec(&raw).unwrap();
|
||||
assert_eq!(verifier.verify(&raw, &parsed).unwrap(), i != 1);
|
||||
}
|
||||
verifier.finish().unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! Wire-format helpers: safe decoding, response construction and UDP truncation.
|
||||
use hickory_proto::op::{Edns, Message, MessageType, OpCode, ResponseCode};
|
||||
|
||||
/// Default EDNS UDP payload we advertise and accept (DNS Flag Day 2020).
|
||||
pub const DEFAULT_EDNS_PAYLOAD: u16 = 1232;
|
||||
/// Absolute maximum size of a DNS message.
|
||||
pub const MAX_MESSAGE: usize = 65_535;
|
||||
|
||||
/// Build an empty response for `req` (copies id, opcode, question, RD, CD).
|
||||
pub fn response_for(req: &Message) -> Message {
|
||||
let mut resp = Message::new(req.metadata.id, MessageType::Response, req.metadata.op_code);
|
||||
resp.metadata.recursion_desired = req.metadata.recursion_desired;
|
||||
resp.metadata.checking_disabled = req.metadata.checking_disabled;
|
||||
resp.queries = req.queries.clone();
|
||||
if let Some(edns) = &req.edns {
|
||||
let mut e = Edns::new();
|
||||
e.set_max_payload(DEFAULT_EDNS_PAYLOAD);
|
||||
e.set_dnssec_ok(edns.flags().dnssec_ok);
|
||||
resp.edns = Some(e);
|
||||
}
|
||||
resp
|
||||
}
|
||||
|
||||
/// Build an error response to a raw packet whose header could be read but
|
||||
/// whose body failed to parse (FORMERR). Returns `None` if even the ID is unreadable.
|
||||
pub fn formerr_from_raw(raw: &[u8]) -> Option<Vec<u8>> {
|
||||
if raw.len() < 12 {
|
||||
return None;
|
||||
}
|
||||
// Never answer a packet that claims to be a response (reflection loop protection).
|
||||
if raw[2] & 0x80 != 0 {
|
||||
return None;
|
||||
}
|
||||
let id = u16::from_be_bytes([raw[0], raw[1]]);
|
||||
let opcode = OpCode::from_u8((raw[2] >> 3) & 0x0f);
|
||||
let msg = Message::error_msg(id, opcode, ResponseCode::FormErr);
|
||||
msg.to_vec().ok()
|
||||
}
|
||||
|
||||
/// Maximum UDP response size a client accepts.
|
||||
pub fn client_udp_limit(req: &Message, server_max: u16) -> usize {
|
||||
let client = req.edns.as_ref().map(|e| e.max_payload().max(512)).unwrap_or(512);
|
||||
client.min(server_max.max(512)) as usize
|
||||
}
|
||||
|
||||
/// Encode `resp` for UDP, setting TC and stripping records when it does not fit.
|
||||
pub fn encode_udp(resp: &Message, limit: usize) -> Option<Vec<u8>> {
|
||||
let bytes = resp.to_vec().ok()?;
|
||||
if bytes.len() <= limit {
|
||||
return Some(bytes);
|
||||
}
|
||||
let mut t = resp.clone();
|
||||
t.answers.clear();
|
||||
t.authorities.clear();
|
||||
t.additionals.clear();
|
||||
t.metadata.truncation = true;
|
||||
t.to_vec().ok()
|
||||
}
|
||||
|
||||
/// Encode for TCP (64 KiB limit, otherwise SERVFAIL).
|
||||
pub fn encode_tcp(resp: &Message) -> Option<Vec<u8>> {
|
||||
match resp.to_vec() {
|
||||
Ok(b) if b.len() <= MAX_MESSAGE => Some(b),
|
||||
_ => {
|
||||
let mut e = response_shell(resp);
|
||||
e.metadata.response_code = ResponseCode::ServFail;
|
||||
e.to_vec().ok()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn response_shell(resp: &Message) -> Message {
|
||||
let mut m = Message::new(resp.metadata.id, MessageType::Response, resp.metadata.op_code);
|
||||
m.queries = resp.queries.clone();
|
||||
m.metadata.recursion_desired = resp.metadata.recursion_desired;
|
||||
m.metadata.recursion_available = resp.metadata.recursion_available;
|
||||
m
|
||||
}
|
||||
|
||||
/// Lightweight check that a response matches the query we sent (anti-spoofing).
|
||||
pub fn response_matches(query: &Message, resp: &Message) -> bool {
|
||||
if resp.metadata.id != query.metadata.id || resp.metadata.message_type != MessageType::Response {
|
||||
return false;
|
||||
}
|
||||
// Some error responses (FORMERR/NOTIMP) legitimately omit the question.
|
||||
if resp.queries.is_empty() {
|
||||
return resp.metadata.response_code != ResponseCode::NoError;
|
||||
}
|
||||
match (query.queries.first(), resp.queries.first()) {
|
||||
(Some(q), Some(r)) => q.query_type == r.query_type && q.query_class == r.query_class && q.name.eq_ignore_root_case(&r.name),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use hickory_proto::op::Query;
|
||||
use hickory_proto::rr::{Name, RData, Record, RecordType, rdata::TXT};
|
||||
|
||||
#[test]
|
||||
fn truncation() {
|
||||
let mut q = Message::query();
|
||||
q.add_query(Query::query(Name::from_ascii("a.example.").unwrap(), RecordType::TXT));
|
||||
let mut r = response_for(&q);
|
||||
for i in 0..40 {
|
||||
r.add_answer(Record::from_rdata(Name::from_ascii("a.example.").unwrap(), 60, RData::TXT(TXT::new(vec![format!("{i:0>30}")]))));
|
||||
}
|
||||
let b = encode_udp(&r, 512).unwrap();
|
||||
let m = Message::from_vec(&b).unwrap();
|
||||
assert!(m.metadata.truncation);
|
||||
assert!(m.answers.is_empty());
|
||||
let b = encode_udp(&r, 4096).unwrap();
|
||||
assert!(!Message::from_vec(&b).unwrap().metadata.truncation);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formerr_raw() {
|
||||
assert!(formerr_from_raw(&[1, 2]).is_none());
|
||||
let raw = [0xab, 0xcd, 0x01, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0xff];
|
||||
let b = formerr_from_raw(&raw).unwrap();
|
||||
let m = Message::from_vec(&b).unwrap();
|
||||
assert_eq!(m.metadata.id, 0xabcd);
|
||||
assert_eq!(m.metadata.response_code, ResponseCode::FormErr);
|
||||
// responses are never answered
|
||||
let raw = [0xab, 0xcd, 0x81, 0, 0, 0, 0, 0, 0, 0, 0, 0];
|
||||
assert!(formerr_from_raw(&raw).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
//! BIND-compatible zone file parsing and emitting.
|
||||
//!
|
||||
//! Parsing is delegated to the (RFC 1035 master-file) parser in hickory-proto,
|
||||
//! including `$ORIGIN`, `$TTL` and `$INCLUDE`. This module flattens the result
|
||||
//! into a list of records and offers a stable, sorted text serialisation.
|
||||
use std::path::Path;
|
||||
|
||||
use hickory_proto::rr::{Name, RData, Record, RecordType};
|
||||
use hickory_proto::serialize::txt::Parser;
|
||||
|
||||
use crate::{CoreError, CoreResult};
|
||||
|
||||
/// Default TTL used when a zone file lacks `$TTL`.
|
||||
pub const DEFAULT_TTL: u32 = 3600;
|
||||
|
||||
/// Maximum accepted zone file size (bytes) to protect against resource exhaustion.
|
||||
pub const MAX_ZONE_FILE_BYTES: u64 = 256 * 1024 * 1024;
|
||||
|
||||
/// Parse zone file text. `path` is used to resolve relative `$INCLUDE`s.
|
||||
///
|
||||
/// When the file has no `$TTL` directive, records without an explicit TTL get
|
||||
/// [`DEFAULT_TTL`] (BIND would use the SOA MINIMUM field and warn).
|
||||
pub fn parse_str(text: &str, origin: &Name, path: Option<&Path>) -> CoreResult<Vec<Record>> {
|
||||
let (pass, extra) = crate::zonefile_ext::extract(text, origin, DEFAULT_TTL)
|
||||
.map_err(|e| CoreError::ZoneFile(format!("{}: {e}", path.map(|p| p.display().to_string()).unwrap_or_else(|| "<text>".into()))))?;
|
||||
let text = format!("$TTL {DEFAULT_TTL}\n$ORIGIN {origin}\n{pass}");
|
||||
let parser = Parser::new(text.as_str(), path.map(Path::to_path_buf), Some(origin.clone()));
|
||||
let (_origin, sets) = parser
|
||||
.parse()
|
||||
.map_err(|e| CoreError::ZoneFile(format!("{}: {e}", path.map(|p| p.display().to_string()).unwrap_or_else(|| "<text>".into()))))?;
|
||||
let mut out = extra;
|
||||
for (_k, set) in sets {
|
||||
for r in set.records_without_rrsigs() {
|
||||
out.push(r.clone());
|
||||
}
|
||||
for r in set.rrsigs() {
|
||||
out.push(r.clone());
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Read and parse a zone file from disk.
|
||||
pub fn parse_file(path: &Path, origin: &Name) -> CoreResult<Vec<Record>> {
|
||||
let meta = std::fs::metadata(path)?;
|
||||
if meta.len() > MAX_ZONE_FILE_BYTES {
|
||||
return Err(CoreError::ZoneFile(format!("{}: file too large ({} bytes)", path.display(), meta.len())));
|
||||
}
|
||||
let text = std::fs::read_to_string(path)?;
|
||||
parse_str(&text, origin, Some(path))
|
||||
}
|
||||
|
||||
/// Serialise records as zone file text: SOA first, then sorted by owner/type.
|
||||
pub fn emit(origin: &Name, records: &[Record]) -> String {
|
||||
let mut recs: Vec<&Record> = records.iter().collect();
|
||||
recs.sort_by(|a, b| {
|
||||
let a_soa = a.record_type() == RecordType::SOA;
|
||||
let b_soa = b.record_type() == RecordType::SOA;
|
||||
b_soa
|
||||
.cmp(&a_soa)
|
||||
.then_with(|| a.name.cmp(&b.name))
|
||||
.then_with(|| u16::from(a.record_type()).cmp(&u16::from(b.record_type())))
|
||||
.then_with(|| a.data.to_string().cmp(&b.data.to_string()))
|
||||
});
|
||||
let mut s = format!("; zone {origin} written by EasyDNS\n$ORIGIN {origin}\n");
|
||||
for r in recs {
|
||||
let data = match &r.data {
|
||||
RData::Unknown { .. } => crate::zonefile_ext::generic_rdata(&r.data).unwrap_or_default(),
|
||||
d => d.to_string(),
|
||||
};
|
||||
let t = match r.record_type() {
|
||||
RecordType::Unknown(c) => format!("TYPE{c}"),
|
||||
t => t.to_string(),
|
||||
};
|
||||
s.push_str(&format!("{} {} {} {} {}\n", r.name, r.ttl, r.dns_class, t, data));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Atomically write `contents` to `path` (temp file + fsync + rename + dir fsync).
|
||||
pub fn atomic_write(path: &Path, contents: &[u8]) -> CoreResult<()> {
|
||||
use std::io::Write;
|
||||
let dir = path.parent().unwrap_or_else(|| Path::new("."));
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let file_name = path.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_else(|| "zone".into());
|
||||
let tmp = dir.join(format!(".{file_name}.tmp.{}", std::process::id()));
|
||||
{
|
||||
let mut f = std::fs::File::create(&tmp)?;
|
||||
f.write_all(contents)?;
|
||||
f.sync_all()?;
|
||||
}
|
||||
std::fs::rename(&tmp, path)?;
|
||||
if let Ok(d) = std::fs::File::open(dir) {
|
||||
let _ = d.sync_all();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const ZONE: &str = r#"
|
||||
$TTL 3600
|
||||
@ IN SOA ns1 hostmaster 2024010101 7200 3600 1209600 300
|
||||
IN NS ns1
|
||||
IN NS ns2.example.net.
|
||||
ns1 IN A 192.0.2.1
|
||||
www 300 IN A 192.0.2.10
|
||||
www IN AAAA 2001:db8::10
|
||||
*.wild IN TXT "wildcard"
|
||||
mail IN MX 10 mx.example.com.
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn parse_and_roundtrip() {
|
||||
let origin = Name::from_ascii("example.com.").unwrap();
|
||||
let recs = parse_str(ZONE, &origin, None).unwrap();
|
||||
assert_eq!(recs.len(), 8);
|
||||
let text = emit(&origin, &recs);
|
||||
assert!(text.lines().nth(2).unwrap().contains("SOA"));
|
||||
let again = parse_str(&text, &origin, None).unwrap();
|
||||
assert_eq!(again.len(), recs.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dnssec_and_generic_types_roundtrip() {
|
||||
let origin = Name::from_ascii("example.").unwrap();
|
||||
let text = r#"$TTL 300
|
||||
@ IN SOA ns hm 1 2 3 4 5
|
||||
IN NS ns
|
||||
@ 3600 IN DNSKEY 257 3 15 ( l02Woi0iS8Aa25FQkUd9RMzZHJpBoRQwAQEX1SxZJA4= )
|
||||
@ IN RRSIG DNSKEY 15 1 3600 20261231000000 20261101000000 12345 example. ( dGVzdHNpZ25hdHVyZQ== )
|
||||
www IN NSEC example. A RRSIG NSEC
|
||||
x IN TYPE65280 \# 3 abcdef
|
||||
y IN A \# 4 c0000201
|
||||
1 IN NSEC3 1 1 12 aabbccdd 2t7b4g4vsa5smi47k61mv5bv1a22bojr A RRSIG
|
||||
@ IN NSEC3PARAM 1 0 12 aabbccdd
|
||||
"#;
|
||||
let recs = parse_str(text, &origin, None).unwrap();
|
||||
assert_eq!(recs.len(), 9);
|
||||
let out = emit(&origin, &recs);
|
||||
let again = parse_str(&out, &origin, None).unwrap();
|
||||
let mut a: Vec<String> = recs.iter().map(|r| format!("{} {} {}", r.name, r.record_type(), r.data)).collect();
|
||||
let mut b: Vec<String> = again.iter().map(|r| format!("{} {} {}", r.name, r.record_type(), r.data)).collect();
|
||||
a.sort();
|
||||
b.sort();
|
||||
assert_eq!(a, b);
|
||||
assert!(out.contains("TYPE65280 \\# 3 abcdef"));
|
||||
assert!(recs.iter().any(|r| r.name.to_string() == "y.example." && r.data.to_string() == "192.0.2.1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_error_is_reported() {
|
||||
let origin = Name::from_ascii("example.com.").unwrap();
|
||||
assert!(parse_str("@ IN A not-an-ip\n", &origin, None).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
//! Zone-file pre-processor for record types the hickory text parser does not accept:
|
||||
//! DNSKEY, CDNSKEY, RRSIG, NSEC, NSEC3, NSEC3PARAM and RFC 3597 generic syntax
|
||||
//! (`TYPE65534 \# 3 abcdef`, or `\#` RDATA for any type).
|
||||
//!
|
||||
//! Every record line is re-emitted with an explicit owner so that removing a special
|
||||
//! line never changes which owner a following continuation line inherits.
|
||||
use data_encoding::{BASE32_DNSSEC, BASE64, HEXUPPER_PERMISSIVE};
|
||||
use hickory_proto::dnssec::rdata::{DNSKEY, DNSSECRData, NSEC, NSEC3, NSEC3PARAM, RRSIG, SigInput};
|
||||
use hickory_proto::dnssec::{Algorithm, Nsec3HashAlgorithm, PublicKeyBuf};
|
||||
use hickory_proto::rr::rdata::NULL;
|
||||
use hickory_proto::rr::{DNSClass, Name, RData, Record, RecordType, SerialNumber};
|
||||
use hickory_proto::serialize::binary::{BinDecoder, Restrict};
|
||||
|
||||
use crate::{CoreError, CoreResult};
|
||||
|
||||
const SPECIAL: &[&str] = &["DNSKEY", "CDNSKEY", "RRSIG", "NSEC", "NSEC3", "NSEC3PARAM"];
|
||||
|
||||
/// Split text into logical lines: comments removed, parenthesised continuations joined.
|
||||
/// Returns (starts_with_whitespace, tokens) per line, keeping quoted strings intact.
|
||||
fn logical_lines(text: &str) -> Vec<(bool, Vec<String>)> {
|
||||
let mut out = Vec::new();
|
||||
let mut tokens: Vec<String> = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut depth = 0i32;
|
||||
let mut in_quote = false;
|
||||
let mut escaped = false;
|
||||
let mut line_start_ws: Option<bool> = None;
|
||||
let mut chars = text.chars().peekable();
|
||||
let flush_tok = |cur: &mut String, tokens: &mut Vec<String>| {
|
||||
if !cur.is_empty() {
|
||||
tokens.push(std::mem::take(cur));
|
||||
}
|
||||
};
|
||||
while let Some(c) = chars.next() {
|
||||
if line_start_ws.is_none() && c != '\n' {
|
||||
line_start_ws = Some(c == ' ' || c == '\t');
|
||||
}
|
||||
if in_quote {
|
||||
cur.push(c);
|
||||
if escaped {
|
||||
escaped = false;
|
||||
} else if c == '\\' {
|
||||
escaped = true;
|
||||
} else if c == '"' {
|
||||
in_quote = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'"' => {
|
||||
in_quote = true;
|
||||
cur.push(c);
|
||||
}
|
||||
'\\' => {
|
||||
cur.push(c);
|
||||
if let Some(n) = chars.next() {
|
||||
cur.push(n);
|
||||
}
|
||||
}
|
||||
';' => {
|
||||
while let Some(&n) = chars.peek() {
|
||||
if n == '\n' {
|
||||
break;
|
||||
}
|
||||
chars.next();
|
||||
}
|
||||
}
|
||||
'(' => {
|
||||
flush_tok(&mut cur, &mut tokens);
|
||||
depth += 1;
|
||||
}
|
||||
')' => {
|
||||
flush_tok(&mut cur, &mut tokens);
|
||||
depth -= 1;
|
||||
}
|
||||
'\n' => {
|
||||
flush_tok(&mut cur, &mut tokens);
|
||||
if depth <= 0 {
|
||||
depth = 0;
|
||||
if !tokens.is_empty() {
|
||||
out.push((line_start_ws.unwrap_or(false), std::mem::take(&mut tokens)));
|
||||
}
|
||||
line_start_ws = None;
|
||||
}
|
||||
}
|
||||
' ' | '\t' | '\r' => flush_tok(&mut cur, &mut tokens),
|
||||
_ => cur.push(c),
|
||||
}
|
||||
}
|
||||
flush_tok(&mut cur, &mut tokens);
|
||||
if !tokens.is_empty() {
|
||||
out.push((line_start_ws.unwrap_or(false), tokens));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn absolute(s: &str, origin: &Name) -> CoreResult<Name> {
|
||||
if s == "@" {
|
||||
return Ok(origin.clone());
|
||||
}
|
||||
let n = Name::from_ascii(s).map_err(|e| CoreError::ZoneFile(format!("bad name '{s}': {e}")))?;
|
||||
if s.ends_with('.') { Ok(n) } else { n.append_domain(origin).map_err(|e| CoreError::ZoneFile(e.to_string())) }
|
||||
}
|
||||
|
||||
fn is_ttl(s: &str) -> bool {
|
||||
s.chars().next().is_some_and(|c| c.is_ascii_digit()) && crate::proto::serialize::txt::parse_ttl(s).is_ok()
|
||||
}
|
||||
|
||||
fn is_class(s: &str) -> bool {
|
||||
matches!(s.to_ascii_uppercase().as_str(), "IN" | "CH" | "HS" | "NONE" | "ANY")
|
||||
}
|
||||
|
||||
fn parse_alg(s: &str) -> CoreResult<Algorithm> {
|
||||
if let Ok(n) = s.parse::<u8>() {
|
||||
return Ok(Algorithm::from_u8(n));
|
||||
}
|
||||
let n = match s.to_ascii_uppercase().as_str() {
|
||||
"RSASHA1" => 5,
|
||||
"RSASHA1-NSEC3-SHA1" | "NSEC3RSASHA1" => 7,
|
||||
"RSASHA256" => 8,
|
||||
"RSASHA512" => 10,
|
||||
"ECDSAP256SHA256" => 13,
|
||||
"ECDSAP384SHA384" => 14,
|
||||
"ED25519" => 15,
|
||||
"ED448" => 16,
|
||||
other => return Err(CoreError::ZoneFile(format!("unknown DNSSEC algorithm {other}"))),
|
||||
};
|
||||
Ok(Algorithm::from_u8(n))
|
||||
}
|
||||
|
||||
/// RRSIG times: YYYYMMDDHHmmSS or a plain integer.
|
||||
fn parse_time(s: &str) -> CoreResult<u32> {
|
||||
if s.len() == 14 && s.chars().all(|c| c.is_ascii_digit()) {
|
||||
let p = |a: usize, b: usize| s[a..b].parse::<i64>().unwrap_or(0);
|
||||
let (y, mo, d, h, mi, se) = (p(0, 4), p(4, 6), p(6, 8), p(8, 10), p(10, 12), p(12, 14));
|
||||
// days from civil (H. Hinnant)
|
||||
let y2 = if mo <= 2 { y - 1 } else { y };
|
||||
let era = y2.div_euclid(400);
|
||||
let yoe = y2 - era * 400;
|
||||
let mp = (mo + 9) % 12;
|
||||
let doy = (153 * mp + 2) / 5 + d - 1;
|
||||
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
|
||||
let days = era * 146_097 + doe - 719_468;
|
||||
return Ok((days * 86_400 + h * 3600 + mi * 60 + se) as u32);
|
||||
}
|
||||
s.parse::<u32>().map_err(|_| CoreError::ZoneFile(format!("bad RRSIG time '{s}'")))
|
||||
}
|
||||
|
||||
fn parse_types(toks: &[String]) -> CoreResult<Vec<RecordType>> {
|
||||
toks.iter()
|
||||
.map(|t| {
|
||||
let u = t.to_ascii_uppercase();
|
||||
if let Some(n) = u.strip_prefix("TYPE") {
|
||||
return n.parse::<u16>().map(RecordType::from).map_err(|_| CoreError::ZoneFile(format!("bad type {t}")));
|
||||
}
|
||||
u.parse::<RecordType>().map_err(|_| CoreError::ZoneFile(format!("bad type {t}")))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn generic(rtype: RecordType, rd: &[String]) -> CoreResult<RData> {
|
||||
// \# <len> <hex...>
|
||||
let len: usize = rd.get(1).and_then(|l| l.parse().ok()).ok_or_else(|| CoreError::ZoneFile("bad \\# length".into()))?;
|
||||
let hex: String = rd[2..].concat();
|
||||
let bytes = HEXUPPER_PERMISSIVE.decode(hex.as_bytes()).map_err(|_| CoreError::ZoneFile("bad \\# hex data".into()))?;
|
||||
if bytes.len() != len {
|
||||
return Err(CoreError::ZoneFile(format!("\\# length {len} does not match data ({} bytes)", bytes.len())));
|
||||
}
|
||||
if matches!(rtype, RecordType::Unknown(_)) {
|
||||
return Ok(RData::Unknown { code: rtype, rdata: NULL::with(bytes) });
|
||||
}
|
||||
let mut d = BinDecoder::new(&bytes);
|
||||
RData::read(&mut d, rtype, Restrict::new(len as u16)).map_err(|e| CoreError::ZoneFile(format!("invalid {rtype} RDATA: {e}")))
|
||||
}
|
||||
|
||||
fn special(rtype: &str, rd: &[String], origin: &Name) -> CoreResult<RData> {
|
||||
let need = |n: usize| -> CoreResult<()> {
|
||||
if rd.len() < n { Err(CoreError::ZoneFile(format!("{rtype}: expected at least {n} fields"))) } else { Ok(()) }
|
||||
};
|
||||
let num = |s: &String| -> CoreResult<u32> { s.parse::<u32>().map_err(|_| CoreError::ZoneFile(format!("{rtype}: bad number '{s}'"))) };
|
||||
Ok(match rtype {
|
||||
"DNSKEY" | "CDNSKEY" => {
|
||||
need(4)?;
|
||||
let flags = num(&rd[0])? as u16;
|
||||
let alg = parse_alg(&rd[2])?;
|
||||
let key = BASE64.decode(rd[3..].concat().as_bytes()).map_err(|_| CoreError::ZoneFile("DNSKEY: bad base64".into()))?;
|
||||
let k = DNSKEY::with_flags(flags, PublicKeyBuf::new(key, alg));
|
||||
if rtype == "DNSKEY" {
|
||||
RData::DNSSEC(DNSSECRData::DNSKEY(k))
|
||||
} else {
|
||||
return Err(CoreError::ZoneFile("CDNSKEY records are not supported in zone files".into()));
|
||||
}
|
||||
}
|
||||
"RRSIG" => {
|
||||
need(9)?;
|
||||
let covered = parse_types(&rd[0..1])?[0];
|
||||
let input = SigInput {
|
||||
type_covered: covered,
|
||||
algorithm: parse_alg(&rd[1])?,
|
||||
num_labels: num(&rd[2])? as u8,
|
||||
original_ttl: num(&rd[3])?,
|
||||
sig_expiration: SerialNumber::new(parse_time(&rd[4])?),
|
||||
sig_inception: SerialNumber::new(parse_time(&rd[5])?),
|
||||
key_tag: num(&rd[6])? as u16,
|
||||
signer_name: absolute(&rd[7], origin)?,
|
||||
};
|
||||
let sig = BASE64.decode(rd[8..].concat().as_bytes()).map_err(|_| CoreError::ZoneFile("RRSIG: bad base64".into()))?;
|
||||
RData::DNSSEC(DNSSECRData::RRSIG(RRSIG::from_sig(input, sig)))
|
||||
}
|
||||
"NSEC" => {
|
||||
need(1)?;
|
||||
RData::DNSSEC(DNSSECRData::NSEC(NSEC::new(absolute(&rd[0], origin)?, parse_types(&rd[1..])?)))
|
||||
}
|
||||
"NSEC3" => {
|
||||
need(5)?;
|
||||
let alg = Nsec3HashAlgorithm::try_from(num(&rd[0])? as u8).map_err(|e| CoreError::ZoneFile(e.to_string()))?;
|
||||
let flags = num(&rd[1])?;
|
||||
let salt = if rd[3] == "-" {
|
||||
Vec::new()
|
||||
} else {
|
||||
HEXUPPER_PERMISSIVE.decode(rd[3].as_bytes()).map_err(|_| CoreError::ZoneFile("NSEC3: bad salt".into()))?
|
||||
};
|
||||
let next = BASE32_DNSSEC
|
||||
.decode(rd[4].to_ascii_lowercase().as_bytes())
|
||||
.map_err(|_| CoreError::ZoneFile("NSEC3: bad next hash".into()))?;
|
||||
RData::DNSSEC(DNSSECRData::NSEC3(NSEC3::new(alg, flags & 1 == 1, num(&rd[2])? as u16, salt, next, parse_types(&rd[5..])?)))
|
||||
}
|
||||
"NSEC3PARAM" => {
|
||||
need(4)?;
|
||||
let alg = Nsec3HashAlgorithm::try_from(num(&rd[0])? as u8).map_err(|e| CoreError::ZoneFile(e.to_string()))?;
|
||||
let salt = if rd[3] == "-" {
|
||||
Vec::new()
|
||||
} else {
|
||||
HEXUPPER_PERMISSIVE.decode(rd[3].as_bytes()).map_err(|_| CoreError::ZoneFile("NSEC3PARAM: bad salt".into()))?
|
||||
};
|
||||
RData::DNSSEC(DNSSECRData::NSEC3PARAM(NSEC3PARAM::new(alg, num(&rd[1])? & 1 == 1, num(&rd[2])? as u16, salt)))
|
||||
}
|
||||
_ => return Err(CoreError::ZoneFile(format!("unsupported type {rtype}"))),
|
||||
})
|
||||
}
|
||||
|
||||
/// Pre-process: returns text for the hickory parser plus records parsed here.
|
||||
pub fn extract(text: &str, origin: &Name, default_ttl: u32) -> CoreResult<(String, Vec<Record>)> {
|
||||
let mut origin = origin.clone();
|
||||
let mut ttl = default_ttl;
|
||||
let mut last_owner: Option<Name> = None;
|
||||
let mut last_ttl: Option<u32> = None;
|
||||
let mut pass = String::with_capacity(text.len());
|
||||
let mut extra = Vec::new();
|
||||
for (ws, toks) in logical_lines(text) {
|
||||
let first = toks[0].to_ascii_uppercase();
|
||||
if first.starts_with('$') {
|
||||
match first.as_str() {
|
||||
"$ORIGIN" => {
|
||||
if let Some(o) = toks.get(1) {
|
||||
origin = absolute(o, &origin)?;
|
||||
}
|
||||
}
|
||||
"$TTL" => {
|
||||
if let Some(t) = toks.get(1) {
|
||||
ttl = crate::proto::serialize::txt::parse_ttl(t).map_err(|e| CoreError::ZoneFile(e.to_string()))?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
pass.push_str(&toks.join(" "));
|
||||
pass.push('\n');
|
||||
continue;
|
||||
}
|
||||
let (owner, mut i) = if ws {
|
||||
(last_owner.clone().ok_or_else(|| CoreError::ZoneFile("record without owner".into()))?, 0)
|
||||
} else {
|
||||
(absolute(&toks[0], &origin)?, 1)
|
||||
};
|
||||
let mut rec_ttl: Option<u32> = None;
|
||||
let mut class = DNSClass::IN;
|
||||
while i < toks.len() {
|
||||
if is_ttl(&toks[i]) && rec_ttl.is_none() {
|
||||
rec_ttl = crate::proto::serialize::txt::parse_ttl(&toks[i]).ok();
|
||||
i += 1;
|
||||
} else if is_class(&toks[i]) {
|
||||
class = toks[i].to_ascii_uppercase().parse().unwrap_or(DNSClass::IN);
|
||||
i += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(tname) = toks.get(i) else {
|
||||
return Err(CoreError::ZoneFile(format!("{owner}: missing record type")));
|
||||
};
|
||||
let tu = tname.to_ascii_uppercase();
|
||||
let rd = &toks[i + 1..];
|
||||
let generic_syntax = rd.first().is_some_and(|t| t == "\\#");
|
||||
let record_ttl = rec_ttl.or(if ws { last_ttl } else { None }).unwrap_or(ttl);
|
||||
last_owner = Some(owner.clone());
|
||||
last_ttl = Some(record_ttl);
|
||||
let rtype_generic = tu.strip_prefix("TYPE").and_then(|n| n.parse::<u16>().ok()).map(RecordType::from);
|
||||
if SPECIAL.contains(&tu.as_str()) || generic_syntax || rtype_generic.is_some() {
|
||||
let data = if generic_syntax {
|
||||
let rt = match rtype_generic {
|
||||
Some(t) => t,
|
||||
None => tu.parse::<RecordType>().map_err(|_| CoreError::ZoneFile(format!("unknown type {tname}")))?,
|
||||
};
|
||||
generic(rt, rd)?
|
||||
} else if let Some(t) = rtype_generic {
|
||||
return Err(CoreError::ZoneFile(format!("{owner} {t}: unknown types must use RFC 3597 \\# syntax")));
|
||||
} else {
|
||||
special(&tu, rd, &origin).map_err(|e| CoreError::ZoneFile(format!("{owner}: {e}")))?
|
||||
};
|
||||
let mut r = Record::from_rdata(owner, record_ttl, data);
|
||||
r.dns_class = class;
|
||||
extra.push(r);
|
||||
continue;
|
||||
}
|
||||
// pass through with explicit owner/TTL/class
|
||||
pass.push_str(&format!("{owner} {record_ttl} {class} "));
|
||||
pass.push_str(&toks[i..].join(" "));
|
||||
pass.push('\n');
|
||||
}
|
||||
Ok((pass, extra))
|
||||
}
|
||||
|
||||
/// RFC 3597 presentation of RDATA (`\# len hex`).
|
||||
pub fn generic_rdata(data: &RData) -> Option<String> {
|
||||
use crate::proto::serialize::binary::BinEncodable;
|
||||
let b = data.to_bytes().ok()?;
|
||||
Some(format!("\\# {} {}", b.len(), data_encoding::HEXLOWER.encode(&b)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn logical_lines_and_comments() {
|
||||
let l = logical_lines("a IN TXT \"x ; not comment\" ; comment\n IN SOA ns hm (\n 1 2 ; c\n 3 4 5 )\n");
|
||||
assert_eq!(l.len(), 2);
|
||||
assert_eq!(l[0].1, vec!["a", "IN", "TXT", "\"x ; not comment\""]);
|
||||
assert!(l[1].0);
|
||||
assert_eq!(l[1].1.len(), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn times() {
|
||||
assert_eq!(parse_time("20260101000000").unwrap(), 1_767_225_600);
|
||||
assert_eq!(parse_time("1767225600").unwrap(), 1_767_225_600);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user