seer-core 0.57.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! Email anti-spoofing posture (SPF, DMARC, MX, MTA-STS, DANE, BIMI), one
//! check per mechanism so a failed lookup marks only that mechanism
//! incomplete. Reads `posture`'s structured fields (verdict, qualifiers,
//! `permerror`, `mx`), never its notes. DMARC is judged on posture's
//! `effective_policy` (the inherited `sp=` rule lives there only), and a
//! record set receivers ignore (several records) counts as no DMARC.

use futures::future::BoxFuture;

use super::{AuditContext, CheckOutput, CheckSpec};
use crate::audit::finding::{Category, Finding, Severity};
use crate::posture::{
    lookup_email_posture, DmarcPolicy, EmailPosture, MailExchangers, PostureVerdict, SpfPolicy,
};

const SPF: &str = "email.spf";
const DMARC: &str = "email.dmarc";
const MX: &str = "email.mx";
const MTA_STS: &str = "email.mta-sts";
const DANE: &str = "email.dane";
const BIMI: &str = "email.bimi";
const E: Category = Category::Email;

pub(crate) const SPEC: CheckSpec = CheckSpec {
    checks: &[
        (SPF, E),
        (DMARC, E),
        (MX, E),
        (MTA_STS, E),
        (DANE, E),
        (BIMI, E),
    ],
    run,
};

#[cfg(test)]
pub(crate) const IDS: &[&str] = &[
    "email.spf.missing",
    "email.spf.permissive",
    "email.spf.invalid",
    "email.dmarc.missing",
    "email.dmarc.policy-none",
    "email.dmarc.partial",
    "email.parked.spoofable",
    "email.mta-sts.missing",
    "email.dane.missing",
    "email.bimi.missing",
];

fn run<'a>(ctx: &'a AuditContext<'a>) -> BoxFuture<'a, CheckOutput> {
    Box::pin(async move {
        match lookup_email_posture(&ctx.auditor.dns, ctx.domain, None).await {
            Ok(posture) => assess(ctx.domain, &posture),
            Err(e) => {
                let mut out = CheckOutput::default();
                for &(check, category) in SPEC.checks {
                    out.failed(check, category, &e);
                }
                out
            }
        }
    })
}

/// The DMARC policy that applies to the domain (posture's
/// `effective_policy`: `sp=` for an inherited record), lowercased.
fn dmarc_policy(d: &DmarcPolicy) -> Option<String> {
    d.effective_policy.as_deref().map(str::to_ascii_lowercase)
}

fn enforcing(d: &DmarcPolicy) -> bool {
    d.present && matches!(dmarc_policy(d).as_deref(), Some("reject" | "quarantine"))
}

/// Maps a posture report to per-mechanism runs and findings. Pure.
pub(crate) fn assess(domain: &str, p: &EmailPosture) -> CheckOutput {
    let mut out = CheckOutput::default();

    if p.spf.verdict == PostureVerdict::Unknown {
        out.incomplete(SPF, E, "SPF lookup failed");
    } else {
        out.ran(SPF, E, spf_findings(domain, &p.spf));
    }

    if p.dmarc.verdict == PostureVerdict::Unknown {
        out.incomplete(DMARC, E, "DMARC lookup failed");
    } else {
        out.ran(DMARC, E, dmarc_findings(domain, &p.dmarc));
    }

    let receives_mail = matches!(p.mx, MailExchangers::Hosts(_));
    match &p.mx {
        MailExchangers::Unknown => out.incomplete(MX, E, "MX lookup failed"),
        MailExchangers::Hosts(_) => out.ran(MX, E, Vec::new()),
        MailExchangers::Null | MailExchangers::Absent => {
            let locked = p.spf.all_qualifier.as_deref() == Some("-")
                && dmarc_policy(&p.dmarc).as_deref() == Some("reject");
            let unknown = p.spf.verdict == PostureVerdict::Unknown
                || p.dmarc.verdict == PostureVerdict::Unknown;
            if locked {
                out.ran(MX, E, Vec::new());
            } else if unknown {
                out.incomplete(MX, E, "SPF or DMARC lookup failed");
            } else {
                out.ran(
                    MX,
                    E,
                    vec![Finding::new(
                        "email.parked.spoofable",
                        E,
                        Severity::Medium,
                        domain,
                        "Domain sends no mail but can still be spoofed",
                    )
                    .fix("Publish `v=spf1 -all` and a DMARC `p=reject` record (and a null MX) for non-mail domains.")],
                );
            }
        }
    }

    // MTA-STS and DANE protect inbound mail: only meaningful with MX hosts.
    for (check, verdict, present, id, severity, title, fix) in [
        (
            MTA_STS,
            p.mta_sts.verdict,
            p.mta_sts.present,
            "email.mta-sts.missing",
            Severity::Low,
            "No MTA-STS policy",
            "Publish an MTA-STS policy so senders require TLS to your MX hosts.",
        ),
        (
            DANE,
            p.dane.verdict,
            p.dane
                .records
                .iter()
                .any(|r| r.scope.starts_with("_25._tcp")),
            "email.dane.missing",
            Severity::Info,
            "No DANE TLSA records at the MX hosts",
            "Publish TLSA records at _25._tcp.<mx-host> (needs DNSSEC).",
        ),
    ] {
        match &p.mx {
            MailExchangers::Unknown => out.incomplete(check, E, "MX lookup failed"),
            _ if !receives_mail => out.not_applicable(check, E, "domain receives no mail"),
            _ if verdict == PostureVerdict::Unknown => out.incomplete(check, E, "lookup failed"),
            _ if present => out.ran(check, E, Vec::new()),
            _ => out.ran(
                check,
                E,
                vec![Finding::new(id, E, severity, domain, title).fix(fix)],
            ),
        }
    }

    if matches!(p.mx, MailExchangers::Null | MailExchangers::Absent) {
        out.not_applicable(BIMI, E, "domain receives no mail");
    } else if !enforcing(&p.dmarc) {
        out.not_applicable(BIMI, E, "BIMI requires an enforcing DMARC policy");
    } else if p.bimi.verdict == PostureVerdict::Unknown {
        out.incomplete(BIMI, E, "BIMI lookup failed");
    } else if p.bimi.present {
        out.ran(BIMI, E, Vec::new());
    } else {
        out.ran(
            BIMI,
            E,
            vec![Finding::new(
                "email.bimi.missing",
                E,
                Severity::Info,
                domain,
                "No BIMI record",
            )
            .fix("Publish a BIMI record to show your logo in supporting inboxes.")],
        );
    }

    out
}

fn spf_findings(domain: &str, spf: &SpfPolicy) -> Vec<Finding> {
    if !spf.present {
        return vec![Finding::new(
            "email.spf.missing",
            E,
            Severity::High,
            domain,
            "No SPF record",
        )
        .fix("Publish an SPF record listing your senders and ending in -all.")];
    }
    if let Some(cause) = spf.permerror {
        return vec![Finding::new(
            "email.spf.invalid",
            E,
            Severity::Medium,
            domain,
            "SPF record is invalid (permerror)",
        )
        .evidence(cause.describe())
        .fix("Publish exactly one SPF record within the 10-lookup limit.")];
    }
    match spf.all_qualifier.as_deref() {
        Some("-" | "~") => Vec::new(),
        _ => {
            let mut f = Finding::new(
                "email.spf.permissive",
                E,
                Severity::High,
                domain,
                "SPF allows any sender",
            )
            .fix("End the SPF record in -all (or ~all while testing).");
            if let Some(record) = &spf.record {
                f = f.evidence(record.clone());
            }
            vec![f]
        }
    }
}

fn dmarc_findings(domain: &str, d: &DmarcPolicy) -> Vec<Finding> {
    // Present but `Absent`: several records, so receivers apply none
    // (RFC 7489 ยง6.6.3).
    if d.present && d.verdict == PostureVerdict::Absent {
        return vec![Finding::new(
            "email.dmarc.missing",
            E,
            Severity::High,
            domain,
            "Multiple DMARC records, so none applies",
        )
        .fix("Publish exactly one _dmarc record.")];
    }
    if !d.present {
        return vec![Finding::new(
            "email.dmarc.missing",
            E,
            Severity::High,
            domain,
            "No DMARC record",
        )
        .fix("Publish _dmarc with p=none and rua= reporting, then move to quarantine or reject.")];
    }
    let with_record = |f: Finding| match &d.record {
        Some(r) => f.evidence(r.clone()),
        None => f,
    };
    if !enforcing(d) {
        return vec![with_record(
            Finding::new(
                "email.dmarc.policy-none",
                E,
                Severity::Medium,
                domain,
                "DMARC only monitors (policy none)",
            )
            .fix("Move the DMARC policy to quarantine, then reject."),
        )];
    }
    let partial_pct = d.percent.is_some_and(|pct| pct < 100);
    let weak_sp = d
        .subdomain_policy
        .as_deref()
        .is_some_and(|sp| sp.eq_ignore_ascii_case("none"));
    if partial_pct || weak_sp {
        return vec![with_record(
            Finding::new(
                "email.dmarc.partial",
                E,
                Severity::Low,
                domain,
                "DMARC enforcement is partial",
            )
            .fix("Use pct=100 and an enforcing sp= so every message and subdomain is covered."),
        )];
    }
    Vec::new()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::audit::finding::CheckStatus;
    use crate::posture::{BimiPolicy, DanePolicy, MtaStsPolicy, SpfPermerror, TlsaRecord};

    /// A fully hardened mail domain: no findings.
    fn hardened() -> EmailPosture {
        EmailPosture {
            domain: "example.com".into(),
            spf: SpfPolicy {
                present: true,
                record: Some("v=spf1 -all".into()),
                all_qualifier: Some("-".into()),
                verdict: PostureVerdict::Strict,
                permerror: None,
            },
            dmarc: DmarcPolicy {
                present: true,
                record: Some("v=DMARC1; p=reject".into()),
                policy: Some("reject".into()),
                subdomain_policy: None,
                effective_policy: Some("reject".into()),
                aggregate_reports: vec![],
                percent: None,
                verdict: PostureVerdict::Strict,
            },
            mta_sts: MtaStsPolicy {
                present: true,
                record: Some("v=STSv1; id=1".into()),
                id: Some("1".into()),
                verdict: PostureVerdict::Present,
            },
            bimi: BimiPolicy {
                present: true,
                record: Some("v=BIMI1".into()),
                logo_url: None,
                authority_url: None,
                verdict: PostureVerdict::Present,
            },
            dane: DanePolicy {
                present: true,
                records: vec![TlsaRecord {
                    scope: "_25._tcp.mx.example.com".into(),
                    cert_usage: 3,
                    selector: 1,
                    matching: 1,
                    cert_data: "ab".into(),
                }],
                verdict: PostureVerdict::Present,
            },
            mx: MailExchangers::Hosts(vec!["mx.example.com".into()]),
            notes: vec![],
        }
    }

    fn ids(out: &CheckOutput) -> Vec<&'static str> {
        out.findings.iter().map(|f| f.id).collect()
    }

    #[test]
    fn hardened_domain_is_clean_and_every_check_ran() {
        let out = assess("example.com", &hardened());
        assert!(out.findings.is_empty(), "{:?}", out.findings);
        assert_eq!(out.runs.len(), 6);
        assert!(out.runs.iter().all(|r| r.status == CheckStatus::Ran));
    }

    #[test]
    fn missing_spf_and_dmarc_are_high() {
        let mut p = hardened();
        p.spf.present = false;
        p.spf.verdict = PostureVerdict::Absent;
        p.spf.all_qualifier = None;
        p.dmarc.present = false;
        p.dmarc.policy = None;
        p.dmarc.verdict = PostureVerdict::Absent;
        let out = assess("example.com", &p);
        let ids = ids(&out);
        assert!(ids.contains(&"email.spf.missing"));
        assert!(ids.contains(&"email.dmarc.missing"));
        assert!(
            out.findings.iter().all(|f| f.severity == Severity::High),
            "{:?}",
            out.findings
        );
    }

    #[test]
    fn permissive_and_permerror_spf() {
        let mut p = hardened();
        p.spf.all_qualifier = Some("+".into());
        p.spf.verdict = PostureVerdict::Weak;
        assert_eq!(
            ids(&assess("example.com", &p)),
            vec!["email.spf.permissive"]
        );

        let mut p = hardened();
        p.spf.permerror = Some(SpfPermerror::MultipleRecords);
        p.spf.all_qualifier = None;
        assert_eq!(ids(&assess("example.com", &p)), vec!["email.spf.invalid"]);
    }

    #[test]
    fn dmarc_none_and_partial() {
        let mut p = hardened();
        p.dmarc.policy = Some("none".into());
        p.dmarc.effective_policy = Some("none".into());
        p.dmarc.verdict = PostureVerdict::Weak;
        // BIMI needs an enforcing DMARC: not applicable now, so no BIMI finding.
        assert_eq!(
            ids(&assess("example.com", &p)),
            vec!["email.dmarc.policy-none"]
        );

        let mut p = hardened();
        p.dmarc.percent = Some(50);
        assert_eq!(ids(&assess("example.com", &p)), vec!["email.dmarc.partial"]);
    }

    #[test]
    fn a_failed_mechanism_is_incomplete_not_a_finding() {
        let mut p = hardened();
        p.dmarc.present = false;
        p.dmarc.verdict = PostureVerdict::Unknown;
        let out = assess("example.com", &p);
        assert!(!ids(&out).contains(&"email.dmarc.missing"));
        assert!(out.runs.iter().any(
            |r| r.check == "email.dmarc" && matches!(r.status, CheckStatus::Incomplete { .. })
        ));
    }

    #[test]
    fn a_parked_domain_must_lock_down_spf_and_dmarc() {
        let mut p = hardened();
        p.mx = MailExchangers::Absent;
        p.spf.all_qualifier = Some("~".into());
        let out = assess("example.com", &p);
        assert_eq!(ids(&out), vec!["email.parked.spoofable"]);
        // MTA-STS and DANE do not apply without mail.
        assert!(out
            .runs
            .iter()
            .any(|r| r.check == "email.mta-sts"
                && matches!(r.status, CheckStatus::NotApplicable { .. })));

        let mut p = hardened();
        p.mx = MailExchangers::Null;
        assert!(ids(&assess("example.com", &p)).is_empty());
    }

    #[test]
    fn bimi_does_not_apply_without_mail() {
        // Enforcing DMARC, no BIMI record, but the domain receives no mail.
        for mx in [MailExchangers::Null, MailExchangers::Absent] {
            let mut p = hardened();
            p.mx = mx;
            p.bimi.present = false;
            p.bimi.verdict = PostureVerdict::Absent;
            let out = assess("example.com", &p);
            assert!(!ids(&out).contains(&"email.bimi.missing"), "{:?}", p.mx);
            assert!(out.runs.iter().any(|r| r.check == "email.bimi"
                && r.status
                    == CheckStatus::NotApplicable {
                        reason: "domain receives no mail".into()
                    }));
        }
    }

    #[test]
    fn mail_hardening_gaps_are_low_or_info() {
        let mut p = hardened();
        p.mta_sts.present = false;
        p.mta_sts.verdict = PostureVerdict::Absent;
        p.dane.present = false;
        p.dane.records.clear();
        p.dane.verdict = PostureVerdict::Absent;
        p.bimi.present = false;
        p.bimi.verdict = PostureVerdict::Absent;
        let out = assess("example.com", &p);
        assert_eq!(
            ids(&out),
            vec![
                "email.mta-sts.missing",
                "email.dane.missing",
                "email.bimi.missing"
            ]
        );
        assert!(out.findings.iter().all(|f| IDS.contains(&f.id)));
    }

    fn with_dmarc(domain: &str, at: &str, txts: &[&str]) -> EmailPosture {
        let mut p = hardened();
        p.domain = domain.into();
        p.dmarc = crate::posture::dmarc_from_records(domain, at, txts);
        p
    }

    /// Regression: the audit graded raw `p=`, so a subdomain inheriting
    /// `p=none; sp=reject` was reported as monitoring-only although posture
    /// grades it Strict.
    #[test]
    fn inherited_enforcing_sp_is_not_policy_none() {
        let p = with_dmarc(
            "mail.org.test",
            "org.test",
            &["v=DMARC1; p=none; sp=reject"],
        );
        assert_eq!(p.dmarc.verdict, PostureVerdict::Strict);
        let out = assess("mail.org.test", &p);
        assert!(out.findings.is_empty(), "{:?}", out.findings);
        // Enforcing, so BIMI applies (and is present).
        assert!(out
            .runs
            .iter()
            .any(|r| r.check == "email.bimi" && r.status == CheckStatus::Ran));

        // A parked subdomain under the same record is locked down too.
        let mut parked = p.clone();
        parked.mx = MailExchangers::Absent;
        assert!(ids(&assess("mail.org.test", &parked)).is_empty());
    }

    /// Regression: `p=reject; sp=none` inherited by a subdomain leaves it
    /// unenforced, which the audit missed.
    #[test]
    fn inherited_sp_none_is_policy_none() {
        let p = with_dmarc(
            "mail.org.test",
            "org.test",
            &["v=DMARC1; p=reject; sp=none"],
        );
        assert_eq!(p.dmarc.verdict, PostureVerdict::Weak);
        let out = assess("mail.org.test", &p);
        assert_eq!(ids(&out), vec!["email.dmarc.policy-none"]);
        assert_eq!(out.findings[0].severity, Severity::Medium);

        let mut parked = p.clone();
        parked.mx = MailExchangers::Absent;
        assert_eq!(
            ids(&assess("mail.org.test", &parked)),
            vec!["email.dmarc.policy-none", "email.parked.spoofable"]
        );
    }

    /// The domain's own `p=reject; sp=none`: enforced here, partial for
    /// subdomains.
    #[test]
    fn own_sp_none_is_partial() {
        let p = with_dmarc(
            "example.com",
            "example.com",
            &["v=DMARC1; p=reject; sp=none"],
        );
        assert_eq!(ids(&assess("example.com", &p)), vec!["email.dmarc.partial"]);
    }

    /// Regression: two DMARC records mean receivers apply none (RFC 7489
    /// ยง6.6.3), but the audit reported a Medium policy-none.
    #[test]
    fn multiple_dmarc_records_are_missing() {
        let p = with_dmarc(
            "example.com",
            "example.com",
            &["v=DMARC1; p=reject", "v=DMARC1; p=none"],
        );
        assert!(p.dmarc.present);
        assert_eq!(p.dmarc.verdict, PostureVerdict::Absent);
        let out = assess("example.com", &p);
        assert_eq!(ids(&out), vec!["email.dmarc.missing"]);
        assert_eq!(out.findings[0].severity, Severity::High);
    }
}