seer-core 0.33.0

Core library for Seer domain name utilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! CAA (Certification Authority Authorization) lookup and policy comparison.
//!
//! CAA records (RFC 8659) let domain owners declare which Certificate
//! Authorities may issue certificates for the domain. They are consulted
//! by CAs at issuance time only; they are *not* part of certificate
//! validation. A presented certificate whose issuer is not in the current
//! CAA policy is therefore not necessarily invalid — it may have been
//! issued before the policy was updated, or via a parent zone. See
//! [`ISSUANCE_TIME_NOTE`].

use serde::{Deserialize, Serialize};

use crate::dns::{DnsResolver, RecordData, RecordType};

/// Informational note surfaced alongside every CAA report.
///
/// Explains why an issuer/CAA mismatch is not the same as an invalid cert.
pub const ISSUANCE_TIME_NOTE: &str = "CAA is checked by CAs at issuance time, not by \
clients at validation time. A cert whose issuer is not in the current CAA policy is \
not invalid — it may have been issued before the policy was set, or under a parent \
zone. Treat mismatches as informational.";

/// A single CAA resource record.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CaaRecord {
    /// CAA flags (only `issuer_critical` = 128 is defined).
    pub flags: u8,
    /// Property tag (e.g., `issue`, `issuewild`, `iodef`).
    pub tag: String,
    /// Property value (e.g., `letsencrypt.org` or a URI for `iodef`).
    pub value: String,
}

/// Result of how a presented cert's issuer relates to the CAA policy.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum IssuerCaaMatch {
    /// No CAA records exist (any CA may issue per default).
    NoPolicy,
    /// CAA records exist and at least one `issue`/`issuewild` value plausibly
    /// matches the presented issuer.
    Permitted,
    /// CAA records exist but none of the allowed CAs appear to match the
    /// presented issuer. Informational, not a validation failure.
    Mismatch,
    /// CAA records exist but only contain `iodef` / unknown tags — no
    /// authoritative answer about issuance.
    Indeterminate,
}

/// CAA policy collected for a domain, plus the informational note that
/// callers should surface to users.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CaaPolicy {
    /// Records discovered (may be empty if no policy is set).
    pub records: Vec<CaaRecord>,
    /// Domain at which the records were found. Per RFC 8659 the resolver
    /// climbs the tree until a CAA RRset is encountered, so this may be a
    /// parent of the queried name.
    pub effective_domain: Option<String>,
    /// True iff at least one CAA record was found in the tree-walk.
    pub has_policy: bool,
    /// Result of comparing a presented cert's issuer against the policy.
    /// `None` if no cert was supplied for comparison.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub issuer_match: Option<IssuerCaaMatch>,
    /// Informational note about CAA semantics. Always populated.
    pub note: String,
}

impl CaaPolicy {
    /// Empty policy — used when no CAA records were found anywhere in the tree.
    pub fn empty() -> Self {
        Self {
            records: Vec::new(),
            effective_domain: None,
            has_policy: false,
            issuer_match: None,
            note: ISSUANCE_TIME_NOTE.to_string(),
        }
    }
}

/// Looks up CAA records for `domain`, climbing the DNS tree per RFC 8659
/// section 3 until a record set is found or only a TLD remains.
///
/// Returns an [`CaaPolicy::empty`] on resolver errors — CAA is advisory,
/// so we never want to fail a higher-level check just because a CAA query
/// did not return.
pub async fn lookup_caa(resolver: &DnsResolver, domain: &str) -> CaaPolicy {
    let mut current = domain.trim_end_matches('.').to_ascii_lowercase();

    loop {
        match resolver.resolve(&current, RecordType::CAA, None).await {
            Ok(records) if !records.is_empty() => {
                let caa: Vec<CaaRecord> = records
                    .into_iter()
                    .filter_map(|r| match r.data {
                        RecordData::CAA { flags, tag, value } => Some(CaaRecord {
                            flags,
                            tag: tag.to_ascii_lowercase(),
                            value,
                        }),
                        _ => None,
                    })
                    .collect();

                if !caa.is_empty() {
                    return CaaPolicy {
                        has_policy: true,
                        records: caa,
                        effective_domain: Some(current),
                        issuer_match: None,
                        note: ISSUANCE_TIME_NOTE.to_string(),
                    };
                }
            }
            Ok(_) | Err(_) => {}
        }

        // Strip the leftmost label. Stop when only one label (TLD) remains.
        match current.split_once('.') {
            Some((_, rest)) if rest.contains('.') => current = rest.to_string(),
            _ => return CaaPolicy::empty(),
        }
    }
}

/// Compares a presented certificate's issuer string against a CAA policy
/// and returns a classification. Pure function — no I/O.
pub fn classify_issuer(issuer: &str, policy: &CaaPolicy) -> IssuerCaaMatch {
    if !policy.has_policy {
        return IssuerCaaMatch::NoPolicy;
    }

    // RFC 8659 §4.1: if any CAA record has the Issuer Critical flag (bit 7,
    // 0x80) set AND its tag is unknown to us, the spec mandates that
    // issuance be treated as forbidden — we cannot honor a critical
    // property we don't understand. Surface that as `Mismatch` so callers
    // see a non-permitted verdict.
    const KNOWN_TAGS: &[&str] = &["issue", "issuewild", "iodef"];
    let critical_unknown = policy
        .records
        .iter()
        .any(|r| (r.flags & 0x80) != 0 && !KNOWN_TAGS.contains(&r.tag.as_str()));
    if critical_unknown {
        return IssuerCaaMatch::Mismatch;
    }

    let issue_values: Vec<String> = policy
        .records
        .iter()
        .filter(|r| r.tag == "issue" || r.tag == "issuewild")
        .map(|r| {
            // RFC 8659 §4.2: value is "<CA domain> [; <parameters>]". We
            // only need the domain portion for matching.
            r.value
                .split(';')
                .next()
                .unwrap_or(&r.value)
                .trim()
                .to_ascii_lowercase()
        })
        .collect();

    if issue_values.is_empty() {
        return IssuerCaaMatch::Indeterminate;
    }

    let issuer_lc = issuer.to_ascii_lowercase();
    let allowed_any = issue_values.iter().any(|v| !v.is_empty());

    let matched = issue_values
        .iter()
        .any(|v| !v.is_empty() && ca_value_matches_issuer(v, &issuer_lc));

    if matched {
        IssuerCaaMatch::Permitted
    } else if allowed_any {
        IssuerCaaMatch::Mismatch
    } else {
        // Only entries are empty-value (";") — issuance is explicitly forbidden,
        // yet a cert exists. Report as mismatch with the informational note.
        IssuerCaaMatch::Mismatch
    }
}

/// Best-effort comparison between a CAA `issue` value (a CA's domain) and a
/// certificate issuer string (typically a CN/O like "Let's Encrypt").
///
/// CAA values are short reverse-DNS-ish labels; issuer strings vary by CA.
/// We use a small alias table for the common public CAs and fall back to a
/// direct substring check.
fn ca_value_matches_issuer(caa_value: &str, issuer_lc: &str) -> bool {
    if issuer_lc.contains(caa_value) {
        return true;
    }
    // Strip the registrable trailing label (e.g. ".org", ".com") to match
    // base names — "letsencrypt" in "let's encrypt".
    let base = caa_value
        .rsplit_once('.')
        .map(|(b, _)| b)
        .unwrap_or(caa_value);
    if !base.is_empty() && issuer_lc.contains(base) {
        return true;
    }
    // Curated aliases for well-known CAs.
    for (cv, aliases) in CA_ALIASES {
        if caa_value == *cv && aliases.iter().any(|a| issuer_lc.contains(a)) {
            return true;
        }
    }
    false
}

/// Hand-maintained map from common CAA `issue` values to substrings that
/// frequently appear in the issuer CN/O of certs from that CA.
const CA_ALIASES: &[(&str, &[&str])] = &[
    ("letsencrypt.org", &["let's encrypt", "letsencrypt"]),
    ("pki.goog", &["google trust services", "gts "]),
    ("digicert.com", &["digicert"]),
    ("sectigo.com", &["sectigo", "comodo"]),
    ("globalsign.com", &["globalsign"]),
    ("amazon.com", &["amazon"]),
    ("amazontrust.com", &["amazon"]),
    ("zerossl.com", &["zerossl"]),
    ("buypass.com", &["buypass"]),
    ("entrust.net", &["entrust"]),
    ("ssl.com", &["ssl.com"]),
    ("certum.pl", &["certum"]),
    ("identrust.com", &["identrust"]),
];

#[cfg(test)]
mod tests {
    use super::*;

    fn policy_with(records: Vec<(&str, &str)>) -> CaaPolicy {
        CaaPolicy {
            records: records
                .into_iter()
                .map(|(tag, value)| CaaRecord {
                    flags: 0,
                    tag: tag.to_string(),
                    value: value.to_string(),
                })
                .collect(),
            effective_domain: Some("example.com".to_string()),
            has_policy: true,
            issuer_match: None,
            note: ISSUANCE_TIME_NOTE.to_string(),
        }
    }

    #[test]
    fn classify_no_policy() {
        assert_eq!(
            classify_issuer("Let's Encrypt R3", &CaaPolicy::empty()),
            IssuerCaaMatch::NoPolicy
        );
    }

    #[test]
    fn classify_indeterminate_when_only_iodef() {
        let policy = policy_with(vec![("iodef", "mailto:sec@example.com")]);
        assert_eq!(
            classify_issuer("Let's Encrypt R3", &policy),
            IssuerCaaMatch::Indeterminate
        );
    }

    #[test]
    fn classify_permitted_letsencrypt() {
        let policy = policy_with(vec![("issue", "letsencrypt.org")]);
        assert_eq!(
            classify_issuer("CN=R3, O=Let's Encrypt", &policy),
            IssuerCaaMatch::Permitted
        );
    }

    #[test]
    fn classify_permitted_via_alias() {
        // Issuer CN/O does not literally contain "pki.goog"; alias table
        // maps it to "Google Trust Services".
        let policy = policy_with(vec![("issue", "pki.goog")]);
        assert_eq!(
            classify_issuer("CN=GTS CA 1C3, O=Google Trust Services LLC", &policy),
            IssuerCaaMatch::Permitted
        );
    }

    #[test]
    fn classify_mismatch_when_only_other_ca_allowed() {
        let policy = policy_with(vec![("issue", "digicert.com")]);
        assert_eq!(
            classify_issuer("CN=R3, O=Let's Encrypt", &policy),
            IssuerCaaMatch::Mismatch
        );
    }

    #[test]
    fn classify_mismatch_when_issuance_forbidden() {
        // A bare `issue ";"` forbids all issuance, yet a cert exists.
        let policy = policy_with(vec![("issue", ";")]);
        assert_eq!(
            classify_issuer("CN=R3, O=Let's Encrypt", &policy),
            IssuerCaaMatch::Mismatch
        );
    }

    #[test]
    fn classify_issuewild_treated_like_issue() {
        let policy = policy_with(vec![("issuewild", "letsencrypt.org")]);
        assert_eq!(
            classify_issuer("CN=R3, O=Let's Encrypt", &policy),
            IssuerCaaMatch::Permitted
        );
    }

    #[test]
    fn empty_policy_has_no_issuer_match_set() {
        let p = CaaPolicy::empty();
        assert!(p.records.is_empty());
        assert!(!p.has_policy);
        assert!(p.issuer_match.is_none());
        assert_eq!(p.note, ISSUANCE_TIME_NOTE);
    }

    /// RFC 8659 §4.1: a CAA record carrying an unknown tag with the Issuer
    /// Critical flag (bit 7 of `flags`) set MUST be treated as forbidding
    /// issuance — we cannot honor a critical property we don't understand.
    #[test]
    fn classify_unknown_critical_tag_forces_mismatch() {
        let policy = CaaPolicy {
            records: vec![
                // Valid issue that would otherwise match Let's Encrypt.
                CaaRecord {
                    flags: 0,
                    tag: "issue".to_string(),
                    value: "letsencrypt.org".to_string(),
                },
                // Unknown tag with critical flag — must veto issuance.
                CaaRecord {
                    flags: 0x80,
                    tag: "auth".to_string(),
                    value: "future-extension".to_string(),
                },
            ],
            effective_domain: Some("example.com".to_string()),
            has_policy: true,
            issuer_match: None,
            note: ISSUANCE_TIME_NOTE.to_string(),
        };
        assert_eq!(
            classify_issuer("CN=R3, O=Let's Encrypt", &policy),
            IssuerCaaMatch::Mismatch,
            "critical unknown tag must veto otherwise-matching issue"
        );
    }

    #[test]
    fn classify_unknown_non_critical_tag_does_not_veto() {
        // Same shape but flags = 0 (non-critical). Per RFC the unknown tag
        // is ignored; the matching `issue` carries through.
        let policy = CaaPolicy {
            records: vec![
                CaaRecord {
                    flags: 0,
                    tag: "issue".to_string(),
                    value: "letsencrypt.org".to_string(),
                },
                CaaRecord {
                    flags: 0,
                    tag: "auth".to_string(),
                    value: "future-extension".to_string(),
                },
            ],
            effective_domain: Some("example.com".to_string()),
            has_policy: true,
            issuer_match: None,
            note: ISSUANCE_TIME_NOTE.to_string(),
        };
        assert_eq!(
            classify_issuer("CN=R3, O=Let's Encrypt", &policy),
            IssuerCaaMatch::Permitted
        );
    }

    #[test]
    fn classify_critical_known_tag_does_not_veto() {
        // A critical `issue` (a known tag) is just a normal critical-issue.
        // It must NOT trip the unknown-critical veto.
        let policy = CaaPolicy {
            records: vec![CaaRecord {
                flags: 0x80,
                tag: "issue".to_string(),
                value: "letsencrypt.org".to_string(),
            }],
            effective_domain: Some("example.com".to_string()),
            has_policy: true,
            issuer_match: None,
            note: ISSUANCE_TIME_NOTE.to_string(),
        };
        assert_eq!(
            classify_issuer("CN=R3, O=Let's Encrypt", &policy),
            IssuerCaaMatch::Permitted
        );
    }
}