1use serde::{Deserialize, Serialize};
12
13use crate::dns::{DnsResolver, RecordData, RecordType};
14
15pub const ISSUANCE_TIME_NOTE: &str = "CAA is checked by CAs at issuance time, not by \
19clients at validation time. A cert whose issuer is not in the current CAA policy is \
20not invalid — it may have been issued before the policy was set, or under a parent \
21zone. Treat mismatches as informational.";
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct CaaRecord {
26 pub flags: u8,
28 pub tag: String,
30 pub value: String,
32}
33
34#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
36#[serde(rename_all = "lowercase")]
37pub enum IssuerCaaMatch {
38 NoPolicy,
40 Permitted,
43 Mismatch,
46 Indeterminate,
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct CaaPolicy {
55 pub records: Vec<CaaRecord>,
57 pub effective_domain: Option<String>,
61 pub has_policy: bool,
63 #[serde(skip_serializing_if = "Option::is_none")]
66 pub issuer_match: Option<IssuerCaaMatch>,
67 #[serde(default, skip_serializing_if = "Vec::is_empty")]
70 pub iodef: Vec<String>,
71 #[serde(default, skip_serializing_if = "Option::is_none")]
77 pub wildcard_note: Option<String>,
78 pub note: String,
80}
81
82impl CaaPolicy {
83 pub fn empty() -> Self {
85 Self {
86 records: Vec::new(),
87 effective_domain: None,
88 has_policy: false,
89 issuer_match: None,
90 iodef: Vec::new(),
91 wildcard_note: None,
92 note: ISSUANCE_TIME_NOTE.to_string(),
93 }
94 }
95
96 fn from_records(records: Vec<CaaRecord>, effective_domain: String) -> Self {
99 let iodef = records
100 .iter()
101 .filter(|r| r.tag == "iodef")
102 .map(|r| r.value.clone())
103 .filter(|v| !v.is_empty())
104 .collect();
105 let wildcard_note = analyze_wildcard(&records);
106 Self {
107 has_policy: true,
108 records,
109 effective_domain: Some(effective_domain),
110 issuer_match: None,
111 iodef,
112 wildcard_note,
113 note: ISSUANCE_TIME_NOTE.to_string(),
114 }
115 }
116}
117
118fn permitted_cas(records: &[CaaRecord], tag: &str) -> Vec<String> {
122 records
123 .iter()
124 .filter(|r| r.tag == tag)
125 .map(|r| {
126 r.value
127 .split(';')
128 .next()
129 .unwrap_or(&r.value)
130 .trim()
131 .to_ascii_lowercase()
132 })
133 .filter(|v| !v.is_empty())
134 .collect()
135}
136
137fn analyze_wildcard(records: &[CaaRecord]) -> Option<String> {
145 let has_issue = records.iter().any(|r| r.tag == "issue");
146 let has_issuewild = records.iter().any(|r| r.tag == "issuewild");
147 if !has_issue || !has_issuewild {
148 return None;
149 }
150 let issue = permitted_cas(records, "issue");
151 let issuewild = permitted_cas(records, "issuewild");
152 let looser: Vec<String> = issuewild
153 .iter()
154 .filter(|w| !issue.iter().any(|i| i == *w))
155 .cloned()
156 .collect();
157 if looser.is_empty() {
158 None
159 } else {
160 Some(format!(
161 "issuewild permits CA(s) not allowed by issue ({}) — wildcard issuance is broader than named issuance",
162 looser.join(", ")
163 ))
164 }
165}
166
167pub async fn lookup_caa(resolver: &DnsResolver, domain: &str) -> CaaPolicy {
174 let mut current = domain.trim_end_matches('.').to_ascii_lowercase();
175
176 loop {
177 match resolver.resolve(¤t, RecordType::CAA, None).await {
178 Ok(records) if !records.is_empty() => {
179 let caa: Vec<CaaRecord> = records
180 .into_iter()
181 .filter_map(|r| match r.data {
182 RecordData::CAA { flags, tag, value } => Some(CaaRecord {
183 flags,
184 tag: tag.to_ascii_lowercase(),
185 value,
186 }),
187 _ => None,
188 })
189 .collect();
190
191 if !caa.is_empty() {
192 return CaaPolicy::from_records(caa, current);
193 }
194 }
195 Ok(_) | Err(_) => {}
196 }
197
198 match current.split_once('.') {
200 Some((_, rest)) if rest.contains('.') => current = rest.to_string(),
201 _ => return CaaPolicy::empty(),
202 }
203 }
204}
205
206pub fn classify_issuer(issuer: &str, policy: &CaaPolicy) -> IssuerCaaMatch {
209 if !policy.has_policy {
210 return IssuerCaaMatch::NoPolicy;
211 }
212
213 const KNOWN_TAGS: &[&str] = &["issue", "issuewild", "iodef"];
219 let critical_unknown = policy
220 .records
221 .iter()
222 .any(|r| (r.flags & 0x80) != 0 && !KNOWN_TAGS.contains(&r.tag.as_str()));
223 if critical_unknown {
224 return IssuerCaaMatch::Mismatch;
225 }
226
227 let issue_values: Vec<String> = policy
228 .records
229 .iter()
230 .filter(|r| r.tag == "issue" || r.tag == "issuewild")
231 .map(|r| {
232 r.value
235 .split(';')
236 .next()
237 .unwrap_or(&r.value)
238 .trim()
239 .to_ascii_lowercase()
240 })
241 .collect();
242
243 if issue_values.is_empty() {
244 return IssuerCaaMatch::Indeterminate;
245 }
246
247 let issuer_lc = issuer.to_ascii_lowercase();
248 let allowed_any = issue_values.iter().any(|v| !v.is_empty());
249
250 let matched = issue_values
251 .iter()
252 .any(|v| !v.is_empty() && ca_value_matches_issuer(v, &issuer_lc));
253
254 if matched {
255 IssuerCaaMatch::Permitted
256 } else if allowed_any {
257 IssuerCaaMatch::Mismatch
258 } else {
259 IssuerCaaMatch::Mismatch
262 }
263}
264
265fn ca_value_matches_issuer(caa_value: &str, issuer_lc: &str) -> bool {
272 if caa_value.len() >= MIN_FALLBACK_BASE_LEN && contains_word(issuer_lc, caa_value) {
279 return true;
280 }
281 for (cv, aliases) in CA_ALIASES {
285 if caa_value == *cv && aliases.iter().any(|a| issuer_lc.contains(a)) {
286 return true;
287 }
288 }
289 let base = caa_value
295 .rsplit_once('.')
296 .map(|(b, _)| b)
297 .unwrap_or(caa_value);
298 base.len() >= MIN_FALLBACK_BASE_LEN && contains_word(issuer_lc, base)
299}
300
301const MIN_FALLBACK_BASE_LEN: usize = 6;
306
307fn contains_word(haystack: &str, needle: &str) -> bool {
312 if needle.is_empty() {
313 return false;
314 }
315 let bytes = haystack.as_bytes();
316 let mut from = 0;
317 while let Some(rel) = haystack[from..].find(needle) {
318 let start = from + rel;
319 let end = start + needle.len();
320 let before_ok = start == 0 || !bytes[start - 1].is_ascii_alphanumeric();
321 let after_ok = end == bytes.len() || !bytes[end].is_ascii_alphanumeric();
322 if before_ok && after_ok {
323 return true;
324 }
325 from = start + 1;
326 }
327 false
328}
329
330const CA_ALIASES: &[(&str, &[&str])] = &[
333 ("letsencrypt.org", &["let's encrypt", "letsencrypt"]),
334 ("pki.goog", &["google trust services", "gts "]),
335 ("digicert.com", &["digicert"]),
336 ("sectigo.com", &["sectigo", "comodo"]),
337 ("globalsign.com", &["globalsign"]),
338 ("amazon.com", &["amazon"]),
339 ("amazontrust.com", &["amazon"]),
340 ("zerossl.com", &["zerossl"]),
341 ("buypass.com", &["buypass"]),
342 ("entrust.net", &["entrust"]),
343 ("ssl.com", &["ssl.com"]),
344 ("certum.pl", &["certum"]),
345 ("identrust.com", &["identrust"]),
346];
347
348#[cfg(test)]
349mod tests {
350 use super::*;
351
352 fn policy_with(records: Vec<(&str, &str)>) -> CaaPolicy {
353 let records = records
356 .into_iter()
357 .map(|(tag, value)| CaaRecord {
358 flags: 0,
359 tag: tag.to_string(),
360 value: value.to_string(),
361 })
362 .collect();
363 CaaPolicy::from_records(records, "example.com".to_string())
364 }
365
366 #[test]
367 fn iodef_contacts_are_extracted() {
368 let policy = policy_with(vec![
369 ("issue", "letsencrypt.org"),
370 ("iodef", "mailto:security@example.com"),
371 ]);
372 assert_eq!(policy.iodef, vec!["mailto:security@example.com"]);
373 }
374
375 #[test]
376 fn wildcard_note_flags_broader_wildcard_policy() {
377 let policy = policy_with(vec![
380 ("issue", "letsencrypt.org"),
381 ("issuewild", "digicert.com"),
382 ]);
383 let note = policy
384 .wildcard_note
385 .expect("looser wildcard policy flagged");
386 assert!(
387 note.contains("digicert.com"),
388 "note names the extra CA: {note}"
389 );
390 }
391
392 #[test]
393 fn wildcard_note_absent_when_issuewild_missing() {
394 let policy = policy_with(vec![("issue", "letsencrypt.org")]);
396 assert!(policy.wildcard_note.is_none());
397 }
398
399 #[test]
400 fn wildcard_note_absent_when_policies_consistent() {
401 let policy = policy_with(vec![
402 ("issue", "letsencrypt.org"),
403 ("issuewild", "letsencrypt.org"),
404 ]);
405 assert!(policy.wildcard_note.is_none());
406 }
407
408 #[test]
409 fn classify_no_policy() {
410 assert_eq!(
411 classify_issuer("Let's Encrypt R3", &CaaPolicy::empty()),
412 IssuerCaaMatch::NoPolicy
413 );
414 }
415
416 #[test]
417 fn classify_indeterminate_when_only_iodef() {
418 let policy = policy_with(vec![("iodef", "mailto:sec@example.com")]);
419 assert_eq!(
420 classify_issuer("Let's Encrypt R3", &policy),
421 IssuerCaaMatch::Indeterminate
422 );
423 }
424
425 #[test]
426 fn classify_permitted_letsencrypt() {
427 let policy = policy_with(vec![("issue", "letsencrypt.org")]);
428 assert_eq!(
429 classify_issuer("CN=R3, O=Let's Encrypt", &policy),
430 IssuerCaaMatch::Permitted
431 );
432 }
433
434 #[test]
435 fn classify_permitted_via_alias() {
436 let policy = policy_with(vec![("issue", "pki.goog")]);
439 assert_eq!(
440 classify_issuer("CN=GTS CA 1C3, O=Google Trust Services LLC", &policy),
441 IssuerCaaMatch::Permitted
442 );
443 }
444
445 #[test]
446 fn classify_mismatch_when_only_other_ca_allowed() {
447 let policy = policy_with(vec![("issue", "digicert.com")]);
448 assert_eq!(
449 classify_issuer("CN=R3, O=Let's Encrypt", &policy),
450 IssuerCaaMatch::Mismatch
451 );
452 }
453
454 #[test]
455 fn classify_verbatim_match_is_length_guarded() {
456 let policy = policy_with(vec![("issue", "ca")]);
461 assert_eq!(
462 classify_issuer("CN=Verisign Class 3 CA, O=Symantec", &policy),
463 IssuerCaaMatch::Mismatch,
464 "two-letter verbatim CAA value must not over-match unrelated issuers"
465 );
466 }
467
468 #[test]
469 fn classify_full_domain_verbatim_still_matches() {
470 let policy = policy_with(vec![("issue", "letsencrypt.org")]);
473 assert_eq!(
474 classify_issuer("CN=R3, O=letsencrypt.org", &policy),
475 IssuerCaaMatch::Permitted,
476 "full-domain verbatim value must still match"
477 );
478 }
479
480 #[test]
481 fn classify_does_not_overmatch_short_base_substring() {
482 let policy = policy_with(vec![("issue", "ssl.com")]);
486 assert_eq!(
487 classify_issuer("CN=WoanWolf SSL Root CA, O=Other", &policy),
488 IssuerCaaMatch::Mismatch,
489 "bare 'ssl' substring must not over-match"
490 );
491 assert_eq!(
493 classify_issuer("CN=SSL.com RSA SSL subCA, O=SSL Corp", &policy),
494 IssuerCaaMatch::Permitted
495 );
496 }
497
498 #[test]
499 fn classify_unknown_ca_base_matches_only_on_word_boundary() {
500 let policy = policy_with(vec![("issue", "examplecorp.test")]);
503 assert_eq!(
504 classify_issuer("CN=ExampleCorp Root, O=ExampleCorp", &policy),
505 IssuerCaaMatch::Permitted
506 );
507 assert_eq!(
508 classify_issuer("CN=NotExamplecorporated CA", &policy),
509 IssuerCaaMatch::Mismatch,
510 "base inside a larger word must not match"
511 );
512 }
513
514 #[test]
515 fn classify_mismatch_when_issuance_forbidden() {
516 let policy = policy_with(vec![("issue", ";")]);
518 assert_eq!(
519 classify_issuer("CN=R3, O=Let's Encrypt", &policy),
520 IssuerCaaMatch::Mismatch
521 );
522 }
523
524 #[test]
525 fn classify_issuewild_treated_like_issue() {
526 let policy = policy_with(vec![("issuewild", "letsencrypt.org")]);
527 assert_eq!(
528 classify_issuer("CN=R3, O=Let's Encrypt", &policy),
529 IssuerCaaMatch::Permitted
530 );
531 }
532
533 #[test]
534 fn empty_policy_has_no_issuer_match_set() {
535 let p = CaaPolicy::empty();
536 assert!(p.records.is_empty());
537 assert!(!p.has_policy);
538 assert!(p.issuer_match.is_none());
539 assert_eq!(p.note, ISSUANCE_TIME_NOTE);
540 }
541
542 #[test]
546 fn classify_unknown_critical_tag_forces_mismatch() {
547 let policy = CaaPolicy {
548 records: vec![
549 CaaRecord {
551 flags: 0,
552 tag: "issue".to_string(),
553 value: "letsencrypt.org".to_string(),
554 },
555 CaaRecord {
557 flags: 0x80,
558 tag: "auth".to_string(),
559 value: "future-extension".to_string(),
560 },
561 ],
562 effective_domain: Some("example.com".to_string()),
563 has_policy: true,
564 issuer_match: None,
565 iodef: Vec::new(),
566 wildcard_note: None,
567 note: ISSUANCE_TIME_NOTE.to_string(),
568 };
569 assert_eq!(
570 classify_issuer("CN=R3, O=Let's Encrypt", &policy),
571 IssuerCaaMatch::Mismatch,
572 "critical unknown tag must veto otherwise-matching issue"
573 );
574 }
575
576 #[test]
577 fn classify_unknown_non_critical_tag_does_not_veto() {
578 let policy = CaaPolicy {
581 records: vec![
582 CaaRecord {
583 flags: 0,
584 tag: "issue".to_string(),
585 value: "letsencrypt.org".to_string(),
586 },
587 CaaRecord {
588 flags: 0,
589 tag: "auth".to_string(),
590 value: "future-extension".to_string(),
591 },
592 ],
593 effective_domain: Some("example.com".to_string()),
594 has_policy: true,
595 issuer_match: None,
596 iodef: Vec::new(),
597 wildcard_note: None,
598 note: ISSUANCE_TIME_NOTE.to_string(),
599 };
600 assert_eq!(
601 classify_issuer("CN=R3, O=Let's Encrypt", &policy),
602 IssuerCaaMatch::Permitted
603 );
604 }
605
606 #[test]
607 fn classify_critical_known_tag_does_not_veto() {
608 let policy = CaaPolicy {
611 records: vec![CaaRecord {
612 flags: 0x80,
613 tag: "issue".to_string(),
614 value: "letsencrypt.org".to_string(),
615 }],
616 effective_domain: Some("example.com".to_string()),
617 has_policy: true,
618 issuer_match: None,
619 iodef: Vec::new(),
620 wildcard_note: None,
621 note: ISSUANCE_TIME_NOTE.to_string(),
622 };
623 assert_eq!(
624 classify_issuer("CN=R3, O=Let's Encrypt", &policy),
625 IssuerCaaMatch::Permitted
626 );
627 }
628}