1#![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
22pub const MAX_DNS_NAME_BYTES: usize = 253;
24pub const MAX_DNS_LABEL_BYTES: usize = 63;
26
27#[derive(Clone, Copy, Debug, Eq, PartialEq)]
29pub enum TlsaTransport {
30 Tcp,
32 Udp,
34 Sctp,
36}
37
38impl TlsaTransport {
39 #[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#[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 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 #[must_use]
102 pub fn host(&self) -> &str {
103 &self.host
104 }
105
106 #[must_use]
108 pub fn resolver_name(&self) -> &str {
109 &self.resolver_name
110 }
111
112 #[must_use]
114 pub fn fqdn(&self) -> &str {
115 &self.fqdn
116 }
117
118 #[must_use]
120 pub const fn port(&self) -> u16 {
121 self.port
122 }
123
124 #[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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
139pub enum IcannDnssecStatus {
140 Secure,
142 InsecureDelegation,
144 Bogus,
146 Indeterminate,
148}
149
150#[derive(Clone, Copy, Debug, Eq, PartialEq)]
152pub enum ResolverAuthentication {
153 Authenticated,
155 Unauthenticated,
157}
158
159#[derive(Clone, Copy, Debug, Eq, PartialEq)]
161pub enum DnssecQueryMode {
162 Validate,
164 CheckingDisabled,
166 DnssecRecordsNotRequested,
168}
169
170#[derive(Clone, Copy, Debug, Eq, PartialEq)]
172pub enum TlsaDenial {
173 None,
175 Authenticated,
177}
178
179#[derive(Clone, Copy, Debug, Eq, PartialEq)]
181pub struct ValidatingDohEvidence {
182 pub resolver_authentication: ResolverAuthentication,
185 pub query_mode: DnssecQueryMode,
187 pub dnssec: IcannDnssecStatus,
190 pub tlsa_record_count: usize,
193 pub denial: TlsaDenial,
195}
196
197#[derive(Clone, Copy, Debug, Eq, PartialEq)]
199pub enum BrowserTlsDecision {
200 EnforceDane {
202 record_count: NonZeroUsize,
204 },
205 WebPkiAuthenticatedAbsence,
207 WebPkiInsecureDelegation,
210}
211
212impl BrowserTlsDecision {
213 #[must_use]
215 pub const fn enforces_dane(self) -> bool {
216 matches!(self, Self::EnforceDane { .. })
217 }
218
219 #[must_use]
221 pub const fn permits_webpki(self) -> bool {
222 matches!(
223 self,
224 Self::WebPkiAuthenticatedAbsence | Self::WebPkiInsecureDelegation
225 )
226 }
227}
228
229pub 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
274#[non_exhaustive]
275pub enum DiscoveryError {
276 InvalidHost,
278 InvalidPort,
280 NameTooLong,
282 UnauthenticatedResolver,
284 ValidationBypassed,
286 BogusDnssec,
288 IndeterminateDnssec,
290 MissingAuthenticatedDenial,
292 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}