Skip to main content

hns_icann_dane/
lib.rs

1//! Shared automatic ICANN DANE discovery policy for every browser shell.
2//!
3//! This crate is deliberately independent of a DNS or TLS implementation. It
4//! derives the exact TLSA owner for a canonical origin and converts evidence
5//! from a TLS-authenticated validating ICANN DoH resolver into one of two
6//! permitted browser actions: enforce securely present TLSA data, or retain
7//! WebPKI after authenticated absence or a proven-insecure delegation.
8//! Bogus, indeterminate, malformed, and unauthenticated results fail closed.
9
10#![forbid(unsafe_code)]
11#![allow(
12    clippy::doc_markdown,
13    clippy::module_name_repetitions,
14    reason = "DANE, DNSSEC, DoH, ICANN, TLSA, and WebPKI are protocol names"
15)]
16
17use std::fmt;
18use std::net::IpAddr;
19use std::num::NonZeroUsize;
20use std::str::FromStr;
21
22/// Maximum DNS presentation-name length without a terminating root dot.
23pub const MAX_DNS_NAME_BYTES: usize = 253;
24/// Maximum DNS label length.
25pub const MAX_DNS_LABEL_BYTES: usize = 63;
26
27/// Transport label used in a TLSA owner name.
28#[derive(Clone, Copy, Debug, Eq, PartialEq)]
29pub enum TlsaTransport {
30    /// `_tcp`.
31    Tcp,
32    /// `_udp`.
33    Udp,
34    /// `_sctp`.
35    Sctp,
36}
37
38impl TlsaTransport {
39    /// Underscore-prefixed DNS service label.
40    #[must_use]
41    pub const fn label(self) -> &'static str {
42        match self {
43            Self::Tcp => "_tcp",
44            Self::Udp => "_udp",
45            Self::Sctp => "_sctp",
46        }
47    }
48}
49
50/// Canonical service-prefixed TLSA owner.
51#[derive(Clone, Debug, Eq, PartialEq)]
52pub struct TlsaOwner {
53    host: String,
54    resolver_name: String,
55    fqdn: String,
56    port: u16,
57    transport: TlsaTransport,
58}
59
60impl TlsaOwner {
61    /// Derive `_<port>._<transport>.<host>.` from one canonical ASCII DNS host.
62    ///
63    /// URL parsers must apply IDNA before this boundary. Case and a terminating
64    /// root dot are normalized here. IP literals, empty labels, non-host
65    /// characters, zero ports, and DNS names that exceed wire bounds fail.
66    ///
67    /// # Errors
68    ///
69    /// Returns [`DiscoveryError::InvalidHost`],
70    /// [`DiscoveryError::InvalidPort`], or
71    /// [`DiscoveryError::NameTooLong`] when the service owner cannot be
72    /// represented as one absolute DNS name.
73    pub fn derive(host: &str, port: u16, transport: TlsaTransport) -> Result<Self, DiscoveryError> {
74        if port == 0 {
75            return Err(DiscoveryError::InvalidPort);
76        }
77        if host.trim() != host {
78            return Err(DiscoveryError::InvalidHost);
79        }
80        let without_root = host.strip_suffix('.').unwrap_or(host);
81        if without_root.ends_with('.') {
82            return Err(DiscoveryError::InvalidHost);
83        }
84        let normalized = without_root.to_ascii_lowercase();
85        validate_host(&normalized)?;
86        let resolver_name = format!("_{port}.{}.{}", transport.label(), normalized);
87        if resolver_name.len() > MAX_DNS_NAME_BYTES {
88            return Err(DiscoveryError::NameTooLong);
89        }
90        let fqdn = format!("{resolver_name}.");
91        Ok(Self {
92            host: normalized,
93            resolver_name,
94            fqdn,
95            port,
96            transport,
97        })
98    }
99
100    /// Canonical origin host without a root dot.
101    #[must_use]
102    pub fn host(&self) -> &str {
103        &self.host
104    }
105
106    /// Resolver-friendly owner without a terminating root dot.
107    #[must_use]
108    pub fn resolver_name(&self) -> &str {
109        &self.resolver_name
110    }
111
112    /// Absolute DNS owner with a terminating root dot.
113    #[must_use]
114    pub fn fqdn(&self) -> &str {
115        &self.fqdn
116    }
117
118    /// Effective TLS service port.
119    #[must_use]
120    pub const fn port(&self) -> u16 {
121        self.port
122    }
123
124    /// Effective TLS service transport.
125    #[must_use]
126    pub const fn transport(&self) -> TlsaTransport {
127        self.transport
128    }
129}
130
131impl fmt::Display for TlsaOwner {
132    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
133        formatter.write_str(self.fqdn())
134    }
135}
136
137/// DNSSEC state reported for a completed lookup by the validating DoH adapter.
138#[derive(Clone, Copy, Debug, Eq, PartialEq)]
139pub enum IcannDnssecStatus {
140    /// The terminal TLSA data or authenticated denial is DNSSEC-secure.
141    Secure,
142    /// The chain proves that the applicable delegation is unsigned.
143    InsecureDelegation,
144    /// DNSSEC validation failed.
145    Bogus,
146    /// The adapter could not determine a secure or insecure result.
147    Indeterminate,
148}
149
150/// Authentication state of the configured validating DoH resolver.
151#[derive(Clone, Copy, Debug, Eq, PartialEq)]
152pub enum ResolverAuthentication {
153    /// The resolver endpoint passed its configured TLS authentication.
154    Authenticated,
155    /// The DoH channel did not authenticate the configured resolver.
156    Unauthenticated,
157}
158
159/// DNSSEC query mode used for the terminal TLSA request.
160#[derive(Clone, Copy, Debug, Eq, PartialEq)]
161pub enum DnssecQueryMode {
162    /// DNSSEC records were requested and resolver validation remained enabled.
163    Validate,
164    /// The query disabled validation with the CD bit.
165    CheckingDisabled,
166    /// The query did not request DNSSEC records with the DO bit.
167    DnssecRecordsNotRequested,
168}
169
170/// Denial evidence for an empty terminal TLSA result.
171#[derive(Clone, Copy, Debug, Eq, PartialEq)]
172pub enum TlsaDenial {
173    /// No authenticated denial covers TLSA absence.
174    None,
175    /// Secure NSEC/NSEC3 evidence covers TLSA absence.
176    Authenticated,
177}
178
179/// Evidence retained from one terminal validating ICANN DoH lookup.
180#[derive(Clone, Copy, Debug, Eq, PartialEq)]
181pub struct ValidatingDohEvidence {
182    /// The configured validating resolver was authenticated by the DoH TLS
183    /// channel before this DNS response was accepted.
184    pub resolver_authentication: ResolverAuthentication,
185    /// DNSSEC request and validation mode.
186    pub query_mode: DnssecQueryMode,
187    /// Typed DNSSEC outcome. Transport, HTTP, parsing, and response-code errors
188    /// must be represented as `Bogus` or `Indeterminate`, never as absence.
189    pub dnssec: IcannDnssecStatus,
190    /// Number of terminal TLSA records. Unsupported records still count:
191    /// secure presence selects DANE and later validation must fail closed.
192    pub tlsa_record_count: usize,
193    /// Denial evidence for an empty terminal result.
194    pub denial: TlsaDenial,
195}
196
197/// Defined browser trust action after automatic TLSA discovery.
198#[derive(Clone, Copy, Debug, Eq, PartialEq)]
199pub enum BrowserTlsDecision {
200    /// Secure TLSA data is present and must be enforced instead of WebPKI.
201    EnforceDane {
202        /// Nonzero number of terminal TLSA records to validate.
203        record_count: NonZeroUsize,
204    },
205    /// TLSA is securely absent, so the connection retains WebPKI.
206    WebPkiAuthenticatedAbsence,
207    /// The applicable zone is proven insecure, so unsigned TLSA bytes are
208    /// ignored and the connection retains WebPKI.
209    WebPkiInsecureDelegation,
210}
211
212impl BrowserTlsDecision {
213    /// Whether this action requires local DANE certificate validation.
214    #[must_use]
215    pub const fn enforces_dane(self) -> bool {
216        matches!(self, Self::EnforceDane { .. })
217    }
218
219    /// Whether this action permits WebPKI for the origin.
220    #[must_use]
221    pub const fn permits_webpki(self) -> bool {
222        matches!(
223            self,
224            Self::WebPkiAuthenticatedAbsence | Self::WebPkiInsecureDelegation
225        )
226    }
227}
228
229/// Convert validating DoH evidence into the only permitted browser actions.
230///
231/// This function never converts bogus, indeterminate, unauthenticated, or
232/// structurally conflicting evidence into “no TLSA.”
233///
234/// # Errors
235///
236/// Returns a fail-closed [`DiscoveryError`] when resolver authentication or
237/// DNSSEC validation was bypassed, DNSSEC is bogus or indeterminate, or the
238/// presence/denial evidence is incomplete or contradictory.
239pub fn decide_browser_tls(
240    evidence: ValidatingDohEvidence,
241) -> Result<BrowserTlsDecision, DiscoveryError> {
242    if evidence.resolver_authentication != ResolverAuthentication::Authenticated {
243        return Err(DiscoveryError::UnauthenticatedResolver);
244    }
245    if evidence.query_mode != DnssecQueryMode::Validate {
246        return Err(DiscoveryError::ValidationBypassed);
247    }
248
249    match evidence.dnssec {
250        IcannDnssecStatus::Bogus => Err(DiscoveryError::BogusDnssec),
251        IcannDnssecStatus::Indeterminate => Err(DiscoveryError::IndeterminateDnssec),
252        IcannDnssecStatus::InsecureDelegation => {
253            if evidence.denial == TlsaDenial::Authenticated {
254                return Err(DiscoveryError::ConflictingEvidence);
255            }
256            Ok(BrowserTlsDecision::WebPkiInsecureDelegation)
257        }
258        IcannDnssecStatus::Secure => match (
259            NonZeroUsize::new(evidence.tlsa_record_count),
260            evidence.denial,
261        ) {
262            (Some(record_count), TlsaDenial::None) => {
263                Ok(BrowserTlsDecision::EnforceDane { record_count })
264            }
265            (None, TlsaDenial::Authenticated) => Ok(BrowserTlsDecision::WebPkiAuthenticatedAbsence),
266            (Some(_), TlsaDenial::Authenticated) => Err(DiscoveryError::ConflictingEvidence),
267            (None, TlsaDenial::None) => Err(DiscoveryError::MissingAuthenticatedDenial),
268        },
269    }
270}
271
272/// Automatic DANE discovery failure.
273#[derive(Clone, Copy, Debug, Eq, PartialEq)]
274#[non_exhaustive]
275pub enum DiscoveryError {
276    /// Origin host is empty, non-ASCII, malformed, or an IP literal.
277    InvalidHost,
278    /// Effective service port is zero.
279    InvalidPort,
280    /// Derived owner exceeds the DNS presentation/wire bound.
281    NameTooLong,
282    /// The DoH resolver endpoint was not authenticated.
283    UnauthenticatedResolver,
284    /// DNSSEC validation was disabled or DNSSEC records were not requested.
285    ValidationBypassed,
286    /// The validating resolver reported bogus DNSSEC.
287    BogusDnssec,
288    /// No secure or proven-insecure DNSSEC classification was available.
289    IndeterminateDnssec,
290    /// Secure empty data lacked authenticated denial.
291    MissingAuthenticatedDenial,
292    /// Presence, denial, and DNSSEC state contradict one another.
293    ConflictingEvidence,
294}
295
296impl fmt::Display for DiscoveryError {
297    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
298        formatter.write_str(match self {
299            Self::InvalidHost => "invalid canonical DNS host",
300            Self::InvalidPort => "TLSA service port must be nonzero",
301            Self::NameTooLong => "derived TLSA owner exceeds DNS bounds",
302            Self::UnauthenticatedResolver => "validating ICANN DoH resolver is unauthenticated",
303            Self::ValidationBypassed => "ICANN DNSSEC validation was bypassed",
304            Self::BogusDnssec => "ICANN DNSSEC validation is bogus",
305            Self::IndeterminateDnssec => "ICANN DNSSEC validation is indeterminate",
306            Self::MissingAuthenticatedDenial => {
307                "empty secure TLSA result lacks authenticated denial"
308            }
309            Self::ConflictingEvidence => "ICANN TLSA evidence is internally conflicting",
310        })
311    }
312}
313
314impl std::error::Error for DiscoveryError {}
315
316fn validate_host(host: &str) -> Result<(), DiscoveryError> {
317    if host.is_empty()
318        || !host.is_ascii()
319        || host.len() > MAX_DNS_NAME_BYTES
320        || IpAddr::from_str(host).is_ok()
321    {
322        return Err(DiscoveryError::InvalidHost);
323    }
324    for label in host.split('.') {
325        if label.is_empty()
326            || label.len() > MAX_DNS_LABEL_BYTES
327            || label.starts_with('-')
328            || label.ends_with('-')
329            || !label
330                .bytes()
331                .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
332        {
333            return Err(DiscoveryError::InvalidHost);
334        }
335    }
336    Ok(())
337}
338
339#[cfg(test)]
340#[allow(
341    clippy::unwrap_used,
342    reason = "tests fail immediately when a fixture violates its invariant"
343)]
344mod tests {
345    use super::*;
346
347    fn evidence(
348        dnssec: IcannDnssecStatus,
349        tlsa_record_count: usize,
350        authenticated_denial: bool,
351    ) -> ValidatingDohEvidence {
352        ValidatingDohEvidence {
353            resolver_authentication: ResolverAuthentication::Authenticated,
354            query_mode: DnssecQueryMode::Validate,
355            dnssec,
356            tlsa_record_count,
357            denial: if authenticated_denial {
358                TlsaDenial::Authenticated
359            } else {
360                TlsaDenial::None
361            },
362        }
363    }
364
365    #[test]
366    fn derives_host_port_and_transport_without_a_hostname_allowlist() {
367        let https = TlsaOwner::derive("DANE-TEST.DENUOWEB.COM.", 443, TlsaTransport::Tcp).unwrap();
368        assert_eq!(https.host(), "dane-test.denuoweb.com");
369        assert_eq!(https.resolver_name(), "_443._tcp.dane-test.denuoweb.com");
370        assert_eq!(https.fqdn(), "_443._tcp.dane-test.denuoweb.com.");
371        assert_eq!(
372            TlsaOwner::derive("example.com", 8443, TlsaTransport::Udp)
373                .unwrap()
374                .fqdn(),
375            "_8443._udp.example.com."
376        );
377        assert_eq!(
378            TlsaOwner::derive("xn--bcher-kva.example", 9443, TlsaTransport::Sctp)
379                .unwrap()
380                .fqdn(),
381            "_9443._sctp.xn--bcher-kva.example."
382        );
383    }
384
385    #[test]
386    fn rejects_non_dns_origins_and_oversized_service_owners() {
387        for host in [
388            "",
389            " example.com",
390            "example.com ",
391            "example.com..",
392            "127.0.0.1",
393            "::1",
394            "[::1]",
395            "has space.example",
396            "-bad.example",
397            "bad-.example",
398            "bücher.example",
399        ] {
400            assert_eq!(
401                TlsaOwner::derive(host, 443, TlsaTransport::Tcp),
402                Err(DiscoveryError::InvalidHost)
403            );
404        }
405        assert_eq!(
406            TlsaOwner::derive("example.com", 0, TlsaTransport::Tcp),
407            Err(DiscoveryError::InvalidPort)
408        );
409
410        let long_host = [
411            "a".repeat(63),
412            "b".repeat(63),
413            "c".repeat(63),
414            "d".repeat(52),
415        ]
416        .join(".");
417        assert!(long_host.len() <= MAX_DNS_NAME_BYTES);
418        assert_eq!(
419            TlsaOwner::derive(&long_host, 443, TlsaTransport::Tcp),
420            Err(DiscoveryError::NameTooLong)
421        );
422    }
423
424    #[test]
425    fn secure_presence_enforces_dane_even_for_unsupported_records() {
426        let decision = decide_browser_tls(evidence(IcannDnssecStatus::Secure, 2, false)).unwrap();
427        assert_eq!(
428            decision,
429            BrowserTlsDecision::EnforceDane {
430                record_count: NonZeroUsize::new(2).unwrap()
431            }
432        );
433        assert!(decision.enforces_dane());
434        assert!(!decision.permits_webpki());
435    }
436
437    #[test]
438    fn only_authenticated_absence_or_insecure_delegation_permits_webpki() {
439        let absence = decide_browser_tls(evidence(IcannDnssecStatus::Secure, 0, true)).unwrap();
440        assert_eq!(absence, BrowserTlsDecision::WebPkiAuthenticatedAbsence);
441        assert!(absence.permits_webpki());
442
443        let insecure =
444            decide_browser_tls(evidence(IcannDnssecStatus::InsecureDelegation, 4, false)).unwrap();
445        assert_eq!(insecure, BrowserTlsDecision::WebPkiInsecureDelegation);
446        assert!(insecure.permits_webpki());
447    }
448
449    #[test]
450    fn bogus_and_indeterminate_never_become_no_tlsa() {
451        assert_eq!(
452            decide_browser_tls(evidence(IcannDnssecStatus::Bogus, 0, false)),
453            Err(DiscoveryError::BogusDnssec)
454        );
455        assert_eq!(
456            decide_browser_tls(evidence(IcannDnssecStatus::Indeterminate, 0, false)),
457            Err(DiscoveryError::IndeterminateDnssec)
458        );
459        assert_eq!(
460            decide_browser_tls(evidence(IcannDnssecStatus::Secure, 0, false)),
461            Err(DiscoveryError::MissingAuthenticatedDenial)
462        );
463    }
464
465    #[test]
466    fn resolver_authentication_and_dnssec_query_mode_are_mandatory() {
467        let mut untrusted = evidence(IcannDnssecStatus::Secure, 1, false);
468        untrusted.resolver_authentication = ResolverAuthentication::Unauthenticated;
469        assert_eq!(
470            decide_browser_tls(untrusted),
471            Err(DiscoveryError::UnauthenticatedResolver)
472        );
473
474        let mut no_do = evidence(IcannDnssecStatus::Secure, 1, false);
475        no_do.query_mode = DnssecQueryMode::DnssecRecordsNotRequested;
476        assert_eq!(
477            decide_browser_tls(no_do),
478            Err(DiscoveryError::ValidationBypassed)
479        );
480
481        let mut checking_disabled = evidence(IcannDnssecStatus::Secure, 1, false);
482        checking_disabled.query_mode = DnssecQueryMode::CheckingDisabled;
483        assert_eq!(
484            decide_browser_tls(checking_disabled),
485            Err(DiscoveryError::ValidationBypassed)
486        );
487    }
488
489    #[test]
490    fn contradictory_presence_and_denial_fail_closed() {
491        assert_eq!(
492            decide_browser_tls(evidence(IcannDnssecStatus::Secure, 1, true)),
493            Err(DiscoveryError::ConflictingEvidence)
494        );
495        assert_eq!(
496            decide_browser_tls(evidence(IcannDnssecStatus::InsecureDelegation, 0, true,)),
497            Err(DiscoveryError::ConflictingEvidence)
498        );
499    }
500}