use crate::config::Config; use anyhow::{ensure, Result}; use arc_swap::ArcSwap; use futures_util::{stream, StreamExt}; use serde::Serialize; use std::{ collections::{BTreeSet, HashMap}, net::IpAddr, sync::{Arc, LazyLock, Weak}, time::{Duration, Instant, SystemTime, UNIX_EPOCH}, }; use tokio::{sync::Notify, time::MissedTickBehavior}; use tokio_util::sync::CancellationToken; pub const REFRESH_SECONDS: u64 = 60; const MAX_AGE_SECONDS: u64 = 180; const MAX_NAMES: usize = 128; const MAX_ADDRESSES: usize = 32; const PARALLEL_LOOKUPS: usize = 8; const LOOKUP_SECONDS: u64 = 4; #[derive(Clone, Debug)] struct Addresses { ips: Vec, valid_until: Instant, } static CACHE: LazyLock>> = LazyLock::new(|| ArcSwap::from_pointee(HashMap::new())); static DIAGNOSTICS: LazyLock>> = LazyLock::new(|| ArcSwap::from_pointee(HashMap::new())); static CHANGED: LazyLock = LazyLock::new(Notify::new); #[derive(Clone)] struct DnsDiagnostic { checked_unix_ms: u64, error: Option, } /// A read-only view of the live resolver, not a second source of ACL permissions. #[derive(Debug, Serialize)] pub(crate) struct DnsAclStatus { pub hostname: String, pub state: &'static str, pub addresses: Vec, pub last_checked_unix_ms: Option, pub valid_for_seconds: Option, pub error: Option, } pub(crate) fn statuses(config: &Config) -> Result> { let names = configured_hostnames(config)?; let diagnostics = DIAGNOSTICS.load(); let cache = CACHE.load(); let now = Instant::now(); Ok(names.into_iter().map(|name| status_for_name(name, &cache, &diagnostics, now)).collect()) } fn status_for_name( hostname: String, cache: &HashMap, diagnostics: &HashMap, now: Instant, ) -> DnsAclStatus { let latest = diagnostics.get(&hostname); let cached = cache.get(&hostname); let current = cached.filter(|entry| entry.valid_until > now); let state = if current.is_some() { "resolved" } else if latest.is_none() { "pending" } else if latest.is_some_and(|entry| entry.error.is_some()) { "failed" } else { "expired" }; DnsAclStatus { hostname, state, addresses: current.map_or_else(Vec::new, |entry| entry.ips.clone()), last_checked_unix_ms: latest.map(|entry| entry.checked_unix_ms), valid_for_seconds: current.map(|entry| entry.valid_until.duration_since(now).as_secs()), error: latest.and_then(|entry| entry.error.clone()), } } pub(crate) fn matches(name: &str, ip: IpAddr) -> bool { let cache = CACHE.load(); cache.get(name).is_some_and(|entry| { entry.valid_until > Instant::now() && entry.ips.binary_search(&ip).is_ok() }) } pub(crate) fn hostname(value: &str) -> Result { let candidate = value.strip_suffix('.').unwrap_or(value); ensure!( candidate.len() <= 253 && candidate.contains('.'), "ACL DNS name requires a fully qualified hostname" ); ensure!( candidate.is_ascii() && !candidate.contains('/') && !candidate.contains(':'), "invalid ACL DNS name" ); let labels: Vec<_> = candidate.split('.').collect(); ensure!( labels .last() .is_some_and(|part| part.chars().any(|ch| ch.is_ascii_alphabetic())), "invalid ACL DNS name suffix" ); for label in labels { ensure!( !label.is_empty() && label.len() <= 63, "invalid ACL DNS label length" ); ensure!( label.as_bytes()[0].is_ascii_alphanumeric() && label.as_bytes()[label.len() - 1].is_ascii_alphanumeric() && label .bytes() .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-'), "invalid ACL DNS label" ); } Ok(candidate.to_ascii_lowercase()) } pub(crate) fn configured_hostnames(config: &Config) -> Result> { let mut names = BTreeSet::new(); let mut inspect = |acl: Option<&crate::acl::Acl>| -> Result<()> { if let Some(acl) = acl { for rule in &acl.rules { if rule.network.parse::().is_ok() || rule.network.parse::().is_ok() { continue; } let name = hostname(&rule.network)?; ensure!( rule.action == crate::acl::Action::Allow, "dynamic DNS ACL rules only support allow; use static IP/CIDR for deny" ); names.insert(name); ensure!( names.len() <= MAX_NAMES, "too many distinct dynamic DNS ACL names (max 128)" ); } } Ok(()) }; inspect(config.global_security.acl.as_ref())?; for policy in &config.host_policies { inspect(Some(&policy.acl))?; } for profile in &config.acl_profiles { inspect(profile.acl.as_ref())?; } for vhost in &config.vhosts { inspect(vhost.acl.as_ref())?; for route in &vhost.routes { inspect(route.acl.as_ref())?; } } for agent in &config.docker_agents.agents { for assignment in &agent.assignments { inspect(assignment.acl.as_ref())?; } } Ok(names.into_iter().collect()) } fn checked_unix_ms() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_millis() as u64 } fn validate_addresses(mut ips: Vec) -> std::result::Result { ips.sort_unstable(); ips.dedup(); if ips.is_empty() { return Err("DNS response contains no A/AAAA addresses".into()); } if ips.len() > MAX_ADDRESSES { return Err(format!("DNS response exceeds the limit of {MAX_ADDRESSES} unique addresses")); } if ips .iter() .any(|ip| matches!(ip, IpAddr::V6(v6) if v6.to_ipv4_mapped().is_some())) { return Err("DNS response contains an IPv4-mapped IPv6 address".into()); } Ok(Addresses { ips, valid_until: Instant::now() + Duration::from_secs(MAX_AGE_SECONDS), }) } async fn resolve(name: String) -> (String, std::result::Result) { let lookup_name = name.clone(); let answer = tokio::time::timeout( Duration::from_secs(LOOKUP_SECONDS), tokio::net::lookup_host((lookup_name.as_str(), 0u16)), ) .await; let result = match answer { Err(_) => Err(format!("DNS lookup timed out after {LOOKUP_SECONDS} seconds")), Ok(Err(error)) => Err(format!("system DNS resolver returned: {error}")), Ok(Ok(sockets)) => validate_addresses(sockets.map(|socket| socket.ip()).collect()), }; (name, result) } pub(crate) fn config_changed() { CHANGED.notify_one(); } pub(crate) async fn poll_loop(app: Weak, shutdown: CancellationToken) { let mut interval = tokio::time::interval(Duration::from_secs(REFRESH_SECONDS)); interval.set_missed_tick_behavior(MissedTickBehavior::Skip); let mut previous_names = Vec::new(); loop { tokio::select! { _ = shutdown.cancelled() => break, _ = interval.tick() => {}, _ = CHANGED.notified() => {}, } let Some(state) = app.upgrade() else { break; }; let snapshot = state.config.load(); let names = match configured_hostnames(&snapshot.envelope.config) { Ok(names) => names, Err(error) => { tracing::error!(error = %error, "ACL DDNS inventory invalid; dynamic DNS rules fail closed"); CACHE.store(Arc::new(HashMap::new())); DIAGNOSTICS.store(Arc::new(HashMap::new())); continue; } }; drop(snapshot); if names != previous_names { tracing::info!(hostnames = ?names, "ACL DDNS resolver inventory updated"); previous_names = names.clone(); } let results: HashMap<_, _> = tokio::select! { _ = shutdown.cancelled() => break, result = stream::iter(names.iter().cloned()) .map(resolve) .buffer_unordered(PARALLEL_LOOKUPS) .collect() => result, }; let current = state.config.load(); if configured_hostnames(¤t.envelope.config).ok().as_ref() != Some(&names) { CHANGED.notify_one(); continue; } let previous = CACHE.load(); let previous_diagnostics = DIAGNOSTICS.load(); let mut addresses = HashMap::new(); let mut diagnostics = HashMap::new(); for (hostname, result) in results { let checked_unix_ms = checked_unix_ms(); match result { Ok(value) => { if previous.get(&hostname).is_none_or(|old| old.ips != value.ips) || previous_diagnostics.get(&hostname).is_some_and(|old| old.error.is_some()) { tracing::info!(hostname = %hostname, addresses = ?value.ips, "ACL DDNS resolved; allow rule matches only these client addresses"); } addresses.insert(hostname.clone(), value); diagnostics.insert(hostname, DnsDiagnostic { checked_unix_ms, error: None }); } Err(error) => { tracing::warn!(hostname = %hostname, reason = %error, "ACL DDNS resolution failed; hostname allows no client addresses"); diagnostics.insert(hostname, DnsDiagnostic { checked_unix_ms, error: Some(error) }); } } } CACHE.store(Arc::new(addresses)); DIAGNOSTICS.store(Arc::new(diagnostics)); } CACHE.store(Arc::new(HashMap::new())); DIAGNOSTICS.store(Arc::new(HashMap::new())); } #[cfg(test)] include!("tests.rs");