dnskit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dnskit/core/mail.py ADDED
@@ -0,0 +1,1346 @@
1
+ """Check a domain's email DNS setup: MX, SPF, DMARC and DKIM.
2
+
3
+ Each check returns findings (pass / warn / fail) with plain-English explanations and fixes,
4
+ so every front end can present them its own way. Named `mail` to avoid shadowing the
5
+ standard library's `email` package.
6
+ """
7
+
8
+ import base64
9
+ import binascii
10
+ import ipaddress
11
+ import re
12
+ import time
13
+ from collections.abc import Callable, Iterable, Sequence
14
+ from concurrent.futures import ThreadPoolExecutor
15
+ from dataclasses import dataclass
16
+ from enum import StrEnum
17
+
18
+ from dnskit.core.diagnosis import explain
19
+ from dnskit.core.lookup import LookupResult, LookupStatus, _choose_nameservers, _query_one, txt_text
20
+ from dnskit.core.nameservers import ResolverChoice
21
+
22
+ # Selectors tried when no --selector is given: Google Workspace, Microsoft 365 (two), and
23
+ # the defaults of common hosting panels and providers (cPanel, Mailchimp/Mandrill).
24
+ DKIM_SELECTORS: tuple[str, ...] = ("google", "selector1", "selector2", "default", "k1")
25
+
26
+ # RFC 7208 §4.6.4: evaluating an SPF record may cause at most 10 DNS lookups.
27
+ SPF_LOOKUP_LIMIT = 10
28
+
29
+ # What each DMARC policy asks receivers to do with mail that fails DMARC.
30
+ DMARC_POLICIES: dict[str, str] = {
31
+ "none": "monitoring only: mail that fails DMARC is delivered as normal, and receivers "
32
+ "only send reports",
33
+ "quarantine": "mail that fails DMARC is put in the spam or junk folder",
34
+ "reject": "mail that fails DMARC is refused outright",
35
+ }
36
+
37
+ # What an SPF record's final `all` means for mail from servers it doesn't list.
38
+ SPF_ALL_MEANINGS: dict[str, str] = {
39
+ "-": "mail from servers not listed should be rejected (hard fail)",
40
+ "~": "mail from servers not listed is treated as suspicious, usually sent to spam (soft fail)",
41
+ "?": "mail from servers not listed gets no verdict at all (neutral), as if there were no "
42
+ "SPF record",
43
+ "+": "every server on the internet may send mail as this domain",
44
+ }
45
+
46
+ _FAULTS = {
47
+ LookupStatus.SERVFAIL,
48
+ LookupStatus.TIMEOUT,
49
+ LookupStatus.NO_NETWORK,
50
+ LookupStatus.NO_NAMESERVERS,
51
+ }
52
+
53
+ # SPF terms that cost a DNS lookup; `redirect` is a modifier and counted separately.
54
+ _SPF_LOOKUP_MECHANISMS = {"include", "a", "mx", "ptr", "exists"}
55
+ _SPF_MECHANISMS = _SPF_LOOKUP_MECHANISMS | {"all", "ip4", "ip6"}
56
+ _SPF_TYPOS = {"ipv4": "ip4", "ipv6": "ip6", "includes": "include", "inc": "include"}
57
+ _DMARC_TAGS = {"v", "p", "sp", "np", "rua", "ruf", "adkim", "aspf", "pct", "fo", "rf", "ri"}
58
+ _DMARC_TAGS |= {"psd", "t"} # DMARCbis
59
+
60
+ # Bounds on following SPF includes, so a loop or a huge tree can't run away.
61
+ _MAX_SPF_DEPTH = 10
62
+ _MAX_SPF_FETCHES = 40
63
+
64
+ _LABEL = re.compile(r"[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?")
65
+ _SELECTOR = re.compile(r"[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*")
66
+
67
+ # Providers whose MX hosts identify them, and the SPF include they document.
68
+ _PROVIDER_SPF: tuple[tuple[str, str], ...] = (
69
+ (".google.com", "_spf.google.com"),
70
+ (".googlemail.com", "_spf.google.com"),
71
+ (".mail.protection.outlook.com", "spf.protection.outlook.com"),
72
+ )
73
+
74
+
75
+ class CheckStatus(StrEnum):
76
+ PASS = "pass"
77
+ WARN = "warn" # works, but is weak, risky or unusual
78
+ FAIL = "fail" # broken or missing, or couldn't be checked
79
+
80
+
81
+ _RANK = {CheckStatus.PASS: 0, CheckStatus.WARN: 1, CheckStatus.FAIL: 2}
82
+
83
+
84
+ def worst(statuses: Iterable[CheckStatus]) -> CheckStatus:
85
+ """The most severe of `statuses` (PASS when there are none)."""
86
+ return max(statuses, key=_RANK.__getitem__, default=CheckStatus.PASS)
87
+
88
+
89
+ @dataclass(frozen=True)
90
+ class Finding:
91
+ status: CheckStatus
92
+ title: str
93
+ explanation: str
94
+ fix: str = "" # empty when there's nothing to do
95
+
96
+
97
+ class EmailSection:
98
+ """Shared by the four checks: an overall status from their findings."""
99
+
100
+ findings: tuple[Finding, ...]
101
+
102
+ @property
103
+ def status(self) -> CheckStatus:
104
+ return worst(f.status for f in self.findings)
105
+
106
+ @property
107
+ def headline(self) -> Finding | None:
108
+ """The first of the most severe findings: the one-line summary of this check."""
109
+ status = self.status
110
+ return next((f for f in self.findings if f.status is status), None)
111
+
112
+
113
+ @dataclass(frozen=True)
114
+ class MxHost:
115
+ preference: int
116
+ host: str # without the trailing dot; empty for a null MX
117
+ addresses: tuple[str, ...] # A then AAAA
118
+ lookup_status: LookupStatus # OK when it has any address, else why not
119
+
120
+
121
+ @dataclass(frozen=True)
122
+ class MxCheck(EmailSection):
123
+ lookup_status: LookupStatus
124
+ hosts: tuple[MxHost, ...] # by preference
125
+ findings: tuple[Finding, ...]
126
+
127
+ @property
128
+ def null_mx(self) -> bool:
129
+ return any(h.host == "" for h in self.hosts)
130
+
131
+
132
+ @dataclass(frozen=True)
133
+ class SpfLookup:
134
+ term: str # e.g. "include:_spf.google.com" or "redirect=_spf.example.com"
135
+ source: str # the domain whose SPF record contains it
136
+ depth: int # 0 for the checked domain's own record
137
+
138
+
139
+ @dataclass(frozen=True)
140
+ class SpfCheck(EmailSection):
141
+ lookup_status: LookupStatus
142
+ records: tuple[str, ...] # every SPF (v=spf1) record at the domain; should be one
143
+ lookups: tuple[SpfLookup, ...] # every term that costs a DNS lookup, includes expanded
144
+ complete: bool # False when an include couldn't be fetched, so lookups is a lower bound
145
+ findings: tuple[Finding, ...]
146
+
147
+ @property
148
+ def lookup_count(self) -> int:
149
+ return len(self.lookups)
150
+
151
+ @property
152
+ def no_mail(self) -> bool:
153
+ """The record is exactly v=spf1 -all: the domain says it sends no mail at all."""
154
+ return len(self.records) == 1 and self.records[0].lower().split() == ["v=spf1", "-all"]
155
+
156
+
157
+ @dataclass(frozen=True)
158
+ class DmarcCheck(EmailSection):
159
+ name: str # _dmarc.<domain>
160
+ lookup_status: LookupStatus
161
+ records: tuple[str, ...] # every v=DMARC1 record; should be one
162
+ tags: tuple[tuple[str, str], ...] # of the record, when there is exactly one
163
+ findings: tuple[Finding, ...]
164
+
165
+ @property
166
+ def policy(self) -> str | None:
167
+ return dict(self.tags).get("p")
168
+
169
+
170
+ @dataclass(frozen=True)
171
+ class DkimSelector:
172
+ selector: str
173
+ name: str # <selector>._domainkey.<domain>
174
+ lookup_status: LookupStatus
175
+ record: str | None # the DKIM key record, if one was found
176
+ custom: bool = False # given with --selector rather than one of DKIM_SELECTORS
177
+ key_type: str | None = None # "rsa" or "ed25519"
178
+ key_bits: int | None = None # RSA key size
179
+ revoked: bool = False # empty p=: the key has been withdrawn
180
+ malformed: bool = False # p= isn't a usable key
181
+
182
+ @property
183
+ def found(self) -> bool:
184
+ return self.record is not None
185
+
186
+
187
+ @dataclass(frozen=True)
188
+ class DkimCheck(EmailSection):
189
+ selectors: tuple[DkimSelector, ...]
190
+ findings: tuple[Finding, ...]
191
+
192
+
193
+ @dataclass(frozen=True)
194
+ class EmailReport:
195
+ domain: str
196
+ # OK when the checks ran. NXDOMAIN when the domain doesn't exist, or the fault (e.g.
197
+ # TIMEOUT) when every query failed the same way; the checks are then None.
198
+ domain_status: LookupStatus
199
+ nameserver: str
200
+ nameserver_source: str
201
+ elapsed_ms: float
202
+ mx: MxCheck | None = None
203
+ spf: SpfCheck | None = None
204
+ dmarc: DmarcCheck | None = None
205
+ dkim: DkimCheck | None = None
206
+ resolver_choice: ResolverChoice | None = None # None with an explicit nameserver
207
+
208
+ @property
209
+ def checks(self) -> tuple[tuple[str, EmailSection], ...]:
210
+ sections: tuple[tuple[str, EmailSection | None], ...] = (
211
+ ("MX", self.mx),
212
+ ("SPF", self.spf),
213
+ ("DMARC", self.dmarc),
214
+ ("DKIM", self.dkim),
215
+ )
216
+ return tuple((label, s) for label, s in sections if s is not None)
217
+
218
+ @property
219
+ def status(self) -> CheckStatus:
220
+ if self.domain_status is not LookupStatus.OK:
221
+ return CheckStatus.FAIL
222
+ return worst(section.status for _, section in self.checks)
223
+
224
+ @property
225
+ def failed(self) -> bool:
226
+ return self.status is CheckStatus.FAIL
227
+
228
+
229
+ Query = Callable[[str, str], LookupResult]
230
+
231
+
232
+ def email_check(
233
+ domain: str,
234
+ selectors: Sequence[str] = (),
235
+ nameserver: str | None = None,
236
+ timeout: float = 5.0,
237
+ refresh: bool = False,
238
+ ) -> EmailReport:
239
+ """Check `domain`'s MX, SPF, DMARC and DKIM records.
240
+
241
+ DKIM is looked up at each of DKIM_SELECTORS plus any extra `selectors`. Nameserver
242
+ selection works as in `lookup()`. An invalid domain or selector raises ValueError.
243
+ """
244
+ domain = normalize_domain(domain)
245
+ custom = [_validate_selector(s) for s in selectors]
246
+ all_selectors = list(dict.fromkeys([*DKIM_SELECTORS, *custom]))
247
+
248
+ start = time.perf_counter()
249
+ selection = _choose_nameservers(nameserver, refresh)
250
+
251
+ def query(name: str, rtype: str) -> LookupResult:
252
+ return _query_one(name, rtype, selection.nameservers, timeout)
253
+
254
+ def report(
255
+ status: LookupStatus,
256
+ mx: MxCheck | None = None,
257
+ spf: SpfCheck | None = None,
258
+ dmarc: DmarcCheck | None = None,
259
+ dkim: DkimCheck | None = None,
260
+ ) -> EmailReport:
261
+ return EmailReport(
262
+ domain=domain,
263
+ domain_status=status,
264
+ nameserver=selection.nameservers[0],
265
+ nameserver_source=selection.source,
266
+ elapsed_ms=(time.perf_counter() - start) * 1000,
267
+ mx=mx,
268
+ spf=spf,
269
+ dmarc=dmarc,
270
+ dkim=dkim,
271
+ resolver_choice=selection.choice,
272
+ )
273
+
274
+ with ThreadPoolExecutor(max_workers=16) as pool:
275
+ mx_future = pool.submit(query, domain, "MX")
276
+ txt_future = pool.submit(query, domain, "TXT")
277
+ dmarc_future = pool.submit(query, f"_dmarc.{domain}", "TXT")
278
+ dkim_futures = [
279
+ pool.submit(query, f"{s}._domainkey.{domain}", "TXT") for s in all_selectors
280
+ ]
281
+ mx_result = mx_future.result()
282
+ txt_result = txt_future.result()
283
+ dmarc_result = dmarc_future.result()
284
+ dkim_results = [f.result() for f in dkim_futures]
285
+
286
+ status = _domain_status([mx_result, txt_result, dmarc_result, *dkim_results])
287
+ if status is not LookupStatus.OK:
288
+ return report(status)
289
+
290
+ # Resolve the mail servers while following the SPF includes.
291
+ hosts = _mx_hosts(mx_result)
292
+ address_futures = {
293
+ host: (pool.submit(query, host, "A"), pool.submit(query, host, "AAAA"))
294
+ for _, host in hosts
295
+ if host and not _is_ip(host)
296
+ }
297
+ spf = _check_spf(domain, txt_result, pool, query, timeout, hosts)
298
+ addresses = {
299
+ host: (a.result(), aaaa.result()) for host, (a, aaaa) in address_futures.items()
300
+ }
301
+
302
+ mx = _check_mx(domain, mx_result, hosts, addresses, timeout)
303
+ dmarc = _check_dmarc(domain, dmarc_result, timeout)
304
+ dkim = _check_dkim(
305
+ domain, all_selectors, set(custom), dkim_results, timeout, sends_mail=not spf.no_mail
306
+ )
307
+ return report(LookupStatus.OK, mx=mx, spf=spf, dmarc=dmarc, dkim=dkim)
308
+
309
+
310
+ def normalize_domain(text: str) -> str:
311
+ """Lower-case `text` and convert it to its ASCII (IDNA) form, or raise ValueError."""
312
+ name = text.strip().rstrip(".").lower()
313
+ if "@" in name:
314
+ raise ValueError(
315
+ f"'{text}' looks like an email address. Pass just the domain, such as "
316
+ f"{name.rsplit('@', 1)[-1] or 'example.com'}."
317
+ )
318
+ if "/" in name or ":" in name:
319
+ raise ValueError(
320
+ f"'{text}' is not a domain name. Pass just the domain, such as example.com, "
321
+ "without http:// or a path."
322
+ )
323
+ try:
324
+ name = name.encode("idna").decode("ascii")
325
+ except UnicodeError:
326
+ name = ""
327
+ labels = name.split(".")
328
+ if len(labels) < 2 or len(name) > 253 or not all(_LABEL.fullmatch(lb) for lb in labels):
329
+ raise ValueError(f"'{text}' is not a valid domain name. Use a name like example.com.")
330
+ return name
331
+
332
+
333
+ def _validate_selector(text: str) -> str:
334
+ selector = text.strip().rstrip(".")
335
+ if "._domainkey" in selector.lower():
336
+ raise ValueError(
337
+ f"Pass just the DKIM selector, not the full name: '{selector.split('.')[0]}' "
338
+ f"rather than '{text}'."
339
+ )
340
+ if not _SELECTOR.fullmatch(selector):
341
+ raise ValueError(
342
+ f"'{text}' is not a valid DKIM selector. It's the s= value in an email's "
343
+ "DKIM-Signature header, such as google or selector1."
344
+ )
345
+ return selector
346
+
347
+
348
+ def _domain_status(results: Sequence[LookupResult]) -> LookupStatus:
349
+ """NXDOMAIN if the domain doesn't exist; a fault if every query failed that way."""
350
+ if results[0].status is LookupStatus.NXDOMAIN:
351
+ return LookupStatus.NXDOMAIN
352
+ statuses = {r.status for r in results}
353
+ if len(statuses) == 1 and (status := statuses.pop()) in _FAULTS:
354
+ return status
355
+ return LookupStatus.OK
356
+
357
+
358
+ def _couldnt_check(what: str, result: LookupResult, name: str, timeout: float) -> Finding:
359
+ diagnosis = explain(result.status, name, result.rtype, timeout)
360
+ assert diagnosis is not None
361
+ return Finding(
362
+ CheckStatus.FAIL,
363
+ f"Couldn't check {what}: {diagnosis.title[0].lower()}{diagnosis.title[1:]}",
364
+ diagnosis.explanation,
365
+ diagnosis.suggestion,
366
+ )
367
+
368
+
369
+ def _sentence(text: str) -> str:
370
+ """`text` with its first letter capitalised (unlike str.capitalize, the rest is kept)."""
371
+ return text[:1].upper() + text[1:]
372
+
373
+
374
+ def _plural(n: int, word: str, plural: str | None = None) -> str:
375
+ return f"{n} {word if n == 1 else plural or word + 's'}"
376
+
377
+
378
+ def _is_ip(text: str) -> bool:
379
+ try:
380
+ ipaddress.ip_address(text)
381
+ except ValueError:
382
+ return False
383
+ return True
384
+
385
+
386
+ def _txt_records(result: LookupResult) -> list[str]:
387
+ return [txt_text(r.value) for r in result.records]
388
+
389
+
390
+ # --- MX ------------------------------------------------------------------------------------
391
+
392
+
393
+ def _mx_hosts(result: LookupResult) -> list[tuple[int, str]]:
394
+ """(preference, host) pairs, lowest preference first. A null MX has host ""."""
395
+ hosts = []
396
+ for record in result.records:
397
+ preference, _, host = record.value.partition(" ")
398
+ hosts.append((int(preference), host.strip().rstrip(".").lower()))
399
+ return sorted(hosts)
400
+
401
+
402
+ def _host_status(a: LookupResult, aaaa: LookupResult) -> LookupStatus:
403
+ if a.status is LookupStatus.OK or aaaa.status is LookupStatus.OK:
404
+ return LookupStatus.OK
405
+ for status in (a.status, aaaa.status):
406
+ if status in _FAULTS:
407
+ return status
408
+ return a.status # NXDOMAIN or NO_ANSWER
409
+
410
+
411
+ _HOST_PROBLEMS = {
412
+ LookupStatus.NXDOMAIN: "the name doesn't exist",
413
+ LookupStatus.NO_ANSWER: "no A or AAAA record",
414
+ }
415
+
416
+
417
+ def _check_mx(
418
+ domain: str,
419
+ result: LookupResult,
420
+ hosts: list[tuple[int, str]],
421
+ addresses: dict[str, tuple[LookupResult, LookupResult]],
422
+ timeout: float,
423
+ ) -> MxCheck:
424
+ mx_hosts = []
425
+ for preference, host in hosts:
426
+ if host in addresses:
427
+ a, aaaa = addresses[host]
428
+ values = tuple(r.value for r in (*a.records, *aaaa.records))
429
+ mx_hosts.append(MxHost(preference, host, values, _host_status(a, aaaa)))
430
+ else: # null MX or an IP address: nothing to resolve
431
+ status = LookupStatus.OK if _is_ip(host) else LookupStatus.NO_ANSWER
432
+ mx_hosts.append(MxHost(preference, host, (host,) if _is_ip(host) else (), status))
433
+
434
+ def check(findings: list[Finding]) -> MxCheck:
435
+ return MxCheck(result.status, tuple(mx_hosts), tuple(findings))
436
+
437
+ if result.status in _FAULTS:
438
+ return check([_couldnt_check("MX", result, domain, timeout)])
439
+ if not mx_hosts:
440
+ return check(
441
+ [
442
+ Finding(
443
+ CheckStatus.FAIL,
444
+ "No MX records",
445
+ f"{domain} has no MX records, so other mail servers don't know where to "
446
+ "deliver email for it. Some will try the domain's own address instead, "
447
+ "which rarely works.",
448
+ "If this domain should receive email, add the MX records your email "
449
+ "provider gives you. If it never receives email, publish a null MX (one MX "
450
+ 'record with priority 0 and host ".") so senders give up straight away.',
451
+ )
452
+ ]
453
+ )
454
+
455
+ real = [h for h in mx_hosts if h.host]
456
+ if len(real) < len(mx_hosts):
457
+ if not real:
458
+ return check(
459
+ [
460
+ Finding(
461
+ CheckStatus.PASS,
462
+ "Doesn't accept email (null MX)",
463
+ f"{domain} publishes a null MX record, which tells senders it never "
464
+ "receives email.",
465
+ )
466
+ ]
467
+ )
468
+ return check(
469
+ [
470
+ Finding(
471
+ CheckStatus.FAIL,
472
+ "Null MX mixed with real mail servers",
473
+ f"{domain} has a null MX record (meaning it accepts no email) alongside "
474
+ "real MX records. A null MX must be the only MX record, so senders may "
475
+ "treat the domain as not accepting mail.",
476
+ 'Remove the null MX record (priority 0, host ".") if the domain receives '
477
+ "email, or remove the other MX records if it doesn't.",
478
+ )
479
+ ]
480
+ )
481
+
482
+ findings = []
483
+ ip_hosts = [h for h in real if _is_ip(h.host)]
484
+ if ip_hosts:
485
+ listed = ", ".join(h.host for h in ip_hosts)
486
+ findings.append(
487
+ Finding(
488
+ CheckStatus.FAIL,
489
+ "MX record points at an IP address",
490
+ f"MX records must name a mail server, not an IP address ({listed}). Many "
491
+ "senders won't deliver to it.",
492
+ f"Give the server a name with an A record (for example mail.{domain}) and "
493
+ "point the MX record at that name.",
494
+ )
495
+ )
496
+
497
+ named = [h for h in real if not _is_ip(h.host)]
498
+ unresolved = [h for h in named if h.lookup_status is not LookupStatus.OK]
499
+ if unresolved:
500
+ reasons = "; ".join(
501
+ f"{h.host}: "
502
+ + _HOST_PROBLEMS.get(h.lookup_status, f"lookup failed ({h.lookup_status})")
503
+ for h in unresolved
504
+ )
505
+ working = len(real) - len(unresolved)
506
+ faults_only = all(h.lookup_status in _FAULTS for h in unresolved)
507
+ fix = (
508
+ "These lookups failed rather than coming back empty; run the check again, or try "
509
+ "a different resolver."
510
+ if faults_only
511
+ else "Fix the mail server names in the MX records, give those servers A records, "
512
+ "or remove the MX records that point at them."
513
+ )
514
+ if working:
515
+ findings.append(
516
+ Finding(
517
+ CheckStatus.WARN,
518
+ f"{_plural(len(unresolved), 'mail server')} of {len(real)} "
519
+ f"{'has' if len(unresolved) == 1 else 'have'} no IP address",
520
+ f"{reasons}. Senders skip these and use the other mail servers, but it "
521
+ "usually means a typo or a server that has been removed.",
522
+ fix,
523
+ )
524
+ )
525
+ else:
526
+ findings.append(
527
+ Finding(
528
+ CheckStatus.FAIL,
529
+ "No mail server has an IP address",
530
+ f"{reasons}. Senders can't connect to any of {domain}'s mail servers, so "
531
+ "email to it bounces or is delayed.",
532
+ fix,
533
+ )
534
+ )
535
+
536
+ if not findings:
537
+ first = real[0].host
538
+ backups = len(real) - 1
539
+ detail = f"Mail for {domain} goes to {first}"
540
+ detail += (
541
+ f" first (lowest priority number); the other {_plural(backups, 'server')} "
542
+ f"{'is a backup' if backups == 1 else 'are backups'}."
543
+ if backups
544
+ else "."
545
+ )
546
+ findings.append(
547
+ Finding(
548
+ CheckStatus.PASS,
549
+ "1 mail server, with an IP address"
550
+ if len(real) == 1
551
+ else f"{len(real)} mail servers, all with IP addresses",
552
+ detail,
553
+ )
554
+ )
555
+ return check(findings)
556
+
557
+
558
+ # --- SPF -----------------------------------------------------------------------------------
559
+
560
+
561
+ @dataclass(frozen=True)
562
+ class _SpfTerm:
563
+ text: str
564
+ name: str # mechanism or modifier name, lower-case
565
+ qualifier: str # "+", "-", "~" or "?"; "" for a modifier
566
+ value: str # the domain or address after ":" or "=", without any CIDR length
567
+
568
+ @property
569
+ def modifier(self) -> bool:
570
+ return self.qualifier == ""
571
+
572
+
573
+ @dataclass(frozen=True)
574
+ class _ParsedSpf:
575
+ terms: tuple[_SpfTerm, ...]
576
+ errors: tuple[str, ...] # each makes the whole record invalid (permerror)
577
+ unknown_modifiers: tuple[str, ...]
578
+
579
+ def mechanisms(self, *names: str) -> list[_SpfTerm]:
580
+ return [t for t in self.terms if not t.modifier and (not names or t.name in names)]
581
+
582
+ def modifier(self, name: str) -> _SpfTerm | None:
583
+ return next((t for t in self.terms if t.modifier and t.name == name), None)
584
+
585
+ @property
586
+ def all(self) -> _SpfTerm | None:
587
+ return next(iter(self.mechanisms("all")), None)
588
+
589
+ @property
590
+ def redirect(self) -> str | None:
591
+ """The redirect target, unless an `all` makes receivers ignore it."""
592
+ term = self.modifier("redirect")
593
+ return term.value if term is not None and self.all is None else None
594
+
595
+ def lookup_terms(self) -> list[_SpfTerm]:
596
+ terms = self.mechanisms(*_SPF_LOOKUP_MECHANISMS)
597
+ redirect = self.modifier("redirect")
598
+ if redirect is not None and self.all is None:
599
+ terms.append(redirect)
600
+ return terms
601
+
602
+
603
+ def _is_spf(text: str) -> bool:
604
+ lowered = text.strip().lower()
605
+ return lowered == "v=spf1" or lowered.startswith("v=spf1 ")
606
+
607
+
608
+ def _valid_domain_spec(spec: str) -> bool:
609
+ """A target domain; macros (%{...}) can't be checked without a message, so allow them."""
610
+ if "%" in spec:
611
+ return " " not in spec
612
+ labels = spec.rstrip(".").lower().split(".")
613
+ return len(labels) >= 2 and all(_LABEL.fullmatch(lb) for lb in labels)
614
+
615
+
616
+ _DUAL_CIDR = re.compile(r"(?::([^/]+))?(?:/(\d+))?(?://(\d+))?")
617
+
618
+
619
+ def _parse_spf(record: str) -> _ParsedSpf:
620
+ terms: list[_SpfTerm] = []
621
+ errors: list[str] = []
622
+ unknown: list[str] = []
623
+ seen_modifiers: set[str] = set()
624
+
625
+ for text in record.split()[1:]:
626
+ modifier = re.fullmatch(r"([A-Za-z][A-Za-z0-9_.-]*)=(.*)", text)
627
+ if modifier:
628
+ name, value = modifier[1].lower(), modifier[2]
629
+ if name in ("redirect", "exp"):
630
+ if name in seen_modifiers:
631
+ errors.append(f"'{name}=' appears more than once")
632
+ elif not _valid_domain_spec(value):
633
+ errors.append(f"'{text}' needs a domain after '='")
634
+ seen_modifiers.add(name)
635
+ else:
636
+ unknown.append(text)
637
+ terms.append(_SpfTerm(text, name, "", value))
638
+ continue
639
+
640
+ qualifier = text[0] if text[:1] in ("+", "-", "~", "?") else "+"
641
+ body = text[1:] if text[:1] in ("+", "-", "~", "?") else text
642
+ name, rest = re.fullmatch(r"([A-Za-z0-9]*)(.*)", body).groups() # type: ignore[union-attr]
643
+ name = name.lower()
644
+ value = ""
645
+
646
+ if name not in _SPF_MECHANISMS:
647
+ hint = f" (did you mean {_SPF_TYPOS[name]}?)" if name in _SPF_TYPOS else ""
648
+ errors.append(f"unknown term '{text}'{hint}")
649
+ continue
650
+ if name == "all":
651
+ if rest:
652
+ errors.append(f"'{text}': all takes no value")
653
+ elif name in ("include", "exists"):
654
+ value = rest[1:]
655
+ if not rest.startswith(":") or not _valid_domain_spec(value):
656
+ errors.append(f"'{text}' needs a domain, as in {name}:example.com")
657
+ elif name in ("a", "mx", "ptr"):
658
+ match = _DUAL_CIDR.fullmatch(rest)
659
+ value = (match[1] or "") if match else ""
660
+ if (
661
+ not match
662
+ or (value and not _valid_domain_spec(value))
663
+ or (name == "ptr" and (match[2] or match[3]))
664
+ or (match[2] and int(match[2]) > 32)
665
+ or (match[3] and int(match[3]) > 128)
666
+ ):
667
+ errors.append(f"'{text}' isn't a valid {name} mechanism")
668
+ else: # ip4, ip6
669
+ value = rest[1:]
670
+ try:
671
+ network = ipaddress.ip_network(value, strict=False)
672
+ except ValueError:
673
+ network = None
674
+ if not rest.startswith(":") or network is None or network.version != int(name[2]):
675
+ errors.append(f"'{text}' isn't a valid IPv{name[2]} address or range")
676
+ terms.append(_SpfTerm(text, name, qualifier, value))
677
+
678
+ return _ParsedSpf(tuple(terms), tuple(errors), tuple(unknown))
679
+
680
+
681
+ @dataclass(frozen=True)
682
+ class _Fetched:
683
+ """An include or redirect target's SPF record, or why there isn't a usable one."""
684
+
685
+ kind: str # "include" or "redirect": how it was first reached
686
+ status: LookupStatus
687
+ records: tuple[str, ...]
688
+
689
+ @property
690
+ def parsed(self) -> _ParsedSpf | None:
691
+ return _parse_spf(self.records[0]) if len(self.records) == 1 else None
692
+
693
+
694
+ def _spf_targets(parsed: _ParsedSpf) -> dict[str, str]:
695
+ """Include and redirect targets to fetch, mapped to "include" or "redirect".
696
+
697
+ Targets with macros depend on the message being checked, so they can't be followed.
698
+ """
699
+ targets = [("include", t.value) for t in parsed.mechanisms("include")]
700
+ if parsed.redirect:
701
+ targets.append(("redirect", parsed.redirect))
702
+ found: dict[str, str] = {}
703
+ for kind, target in targets:
704
+ if "%" not in target:
705
+ found.setdefault(target.rstrip(".").lower(), kind)
706
+ return found
707
+
708
+
709
+ def _fetch_spf_tree(
710
+ parsed: _ParsedSpf, pool: ThreadPoolExecutor, query: Query
711
+ ) -> dict[str, _Fetched]:
712
+ """Fetch every include/redirect target's SPF record, one level at a time in parallel."""
713
+ fetched: dict[str, _Fetched] = {}
714
+ frontier = _spf_targets(parsed)
715
+ for _ in range(_MAX_SPF_DEPTH):
716
+ targets = list(frontier)[: _MAX_SPF_FETCHES - len(fetched)]
717
+ if not targets:
718
+ break
719
+ for target, result in zip(
720
+ targets, pool.map(lambda t: query(t, "TXT"), targets), strict=True
721
+ ):
722
+ records = tuple(t for t in _txt_records(result) if _is_spf(t))
723
+ fetched[target] = _Fetched(frontier[target], result.status, records)
724
+ frontier = {}
725
+ for target in targets:
726
+ child = fetched[target].parsed
727
+ if child is not None:
728
+ for name, kind in _spf_targets(child).items():
729
+ if name not in fetched:
730
+ frontier.setdefault(name, kind)
731
+ return fetched
732
+
733
+
734
+ def _count_lookups(
735
+ domain: str,
736
+ parsed: _ParsedSpf,
737
+ fetched: dict[str, _Fetched],
738
+ depth: int = 0,
739
+ path: tuple[str, ...] = (),
740
+ ) -> list[SpfLookup]:
741
+ """Every lookup-costing term, depth first, with includes expanded where they occur.
742
+
743
+ A target included twice is counted twice, as receivers evaluate it twice. A loop is
744
+ expanded only once.
745
+ """
746
+ path = (*path, domain)
747
+ lookups = []
748
+ for term in parsed.lookup_terms():
749
+ lookups.append(SpfLookup(term.text, domain, depth))
750
+ target = term.value.rstrip(".").lower()
751
+ if term.name not in ("include", "redirect") or target in path or depth >= _MAX_SPF_DEPTH:
752
+ continue
753
+ child = fetched.get(target)
754
+ if child is not None and child.parsed is not None:
755
+ lookups += _count_lookups(target, child.parsed, fetched, depth + 1, path)
756
+ return lookups
757
+
758
+
759
+ def _spf_example(hosts: list[tuple[int, str]]) -> str:
760
+ for _, host in hosts:
761
+ for suffix, include in _PROVIDER_SPF:
762
+ if host.endswith(suffix):
763
+ return f"v=spf1 include:{include} ~all"
764
+ return "v=spf1 include:<your email provider's SPF domain> ~all"
765
+
766
+
767
+ def _check_spf(
768
+ domain: str,
769
+ result: LookupResult,
770
+ pool: ThreadPoolExecutor,
771
+ query: Query,
772
+ timeout: float,
773
+ mx_hosts: list[tuple[int, str]],
774
+ ) -> SpfCheck:
775
+ records = tuple(t for t in _txt_records(result) if _is_spf(t))
776
+
777
+ def check(
778
+ findings: list[Finding], lookups: Sequence[SpfLookup] = (), complete: bool = True
779
+ ) -> SpfCheck:
780
+ return SpfCheck(result.status, records, tuple(lookups), complete, tuple(findings))
781
+
782
+ if result.status in _FAULTS:
783
+ return check([_couldnt_check("SPF", result, domain, timeout)])
784
+ if not records:
785
+ null_mx = bool(mx_hosts) and all(host == "" for _, host in mx_hosts)
786
+ fix = (
787
+ f"{domain} accepts no email (null MX); if it never sends any either, publish a "
788
+ "TXT record of v=spf1 -all so receivers reject anything claiming to be from it."
789
+ if null_mx
790
+ else f"Publish one TXT record at {domain} listing the servers that send its mail, "
791
+ f"such as: {_spf_example(mx_hosts)}. Your email provider's setup guide gives the "
792
+ "exact include."
793
+ )
794
+ return check(
795
+ [
796
+ Finding(
797
+ CheckStatus.FAIL,
798
+ "No SPF record",
799
+ f"{domain} has no TXT record starting with v=spf1, so receivers can't tell "
800
+ "which servers may send its mail. Spoofed mail is more likely to be "
801
+ "delivered, and genuine mail more likely to land in spam.",
802
+ fix,
803
+ )
804
+ ]
805
+ )
806
+ if len(records) > 1:
807
+ return check(
808
+ [
809
+ Finding(
810
+ CheckStatus.FAIL,
811
+ f"{len(records)} SPF records (only one is allowed)",
812
+ "Receivers treat more than one v=spf1 record as an error (permerror), so "
813
+ "SPF fails for all of this domain's mail.",
814
+ "Merge them into a single TXT record: one v=spf1, every include, ip4 and "
815
+ "ip6 term from both, and one all at the end. Then delete the extra record.",
816
+ )
817
+ ]
818
+ )
819
+
820
+ parsed = _parse_spf(records[0])
821
+ findings = _spf_syntax_findings(parsed)
822
+
823
+ fetched = _fetch_spf_tree(parsed, pool, query)
824
+ lookups = _count_lookups(domain, parsed, fetched)
825
+ complete = True
826
+ for target, child in fetched.items():
827
+ kind = child.kind
828
+ if child.status in _FAULTS:
829
+ complete = False
830
+ findings.append(
831
+ Finding(
832
+ CheckStatus.WARN,
833
+ f"Couldn't check {kind}:{target}",
834
+ f"Looking up {target}'s SPF record failed ({child.status}), so its DNS "
835
+ "lookups aren't counted and its record wasn't checked.",
836
+ "Run the check again, or try a different resolver.",
837
+ )
838
+ )
839
+ elif not child.records:
840
+ findings.append(
841
+ Finding(
842
+ CheckStatus.FAIL,
843
+ f"{kind}:{target} has no SPF record",
844
+ f"{target} "
845
+ + (
846
+ "doesn't exist"
847
+ if child.status is LookupStatus.NXDOMAIN
848
+ else "has no v=spf1 record"
849
+ )
850
+ + ", so receivers treat SPF as broken (permerror) whenever they reach "
851
+ "this term.",
852
+ f"Check the spelling of {target} against your provider's instructions, or "
853
+ "remove the term if you no longer use that service.",
854
+ )
855
+ )
856
+ elif len(child.records) > 1:
857
+ findings.append(
858
+ Finding(
859
+ CheckStatus.FAIL,
860
+ f"{kind}:{target} has {len(child.records)} SPF records",
861
+ f"{target} publishes more than one v=spf1 record, which receivers treat as "
862
+ "an error (permerror) whenever they reach this term.",
863
+ f"Ask whoever runs {target} to fix it, or remove the term.",
864
+ )
865
+ )
866
+ elif child.parsed is not None and child.parsed.errors:
867
+ findings.append(
868
+ Finding(
869
+ CheckStatus.FAIL,
870
+ f"{kind}:{target}'s SPF record is invalid",
871
+ f"{_sentence('; '.join(child.parsed.errors))}. Receivers treat SPF as broken "
872
+ "(permerror) whenever they reach this term.",
873
+ f"Ask whoever runs {target} to fix it, or remove the term.",
874
+ )
875
+ )
876
+
877
+ count = len(lookups)
878
+ counted = f"{count} of {SPF_LOOKUP_LIMIT} DNS lookups"
879
+ if count > SPF_LOOKUP_LIMIT:
880
+ findings.append(
881
+ Finding(
882
+ CheckStatus.FAIL,
883
+ f"Too many DNS lookups ({count} of {SPF_LOOKUP_LIMIT})",
884
+ f"Checking this SPF record takes {count} DNS lookups, counting everything its "
885
+ f"includes pull in. Receivers stop at {SPF_LOOKUP_LIMIT} and treat SPF as "
886
+ "broken (permerror), so SPF fails for all of this domain's mail.",
887
+ "Remove includes for services you no longer use, replace a and mx with the "
888
+ "ip4/ip6 addresses they stand for, or use your provider's flattened SPF if it "
889
+ "offers one.",
890
+ )
891
+ )
892
+
893
+ if not any(f.status is CheckStatus.FAIL for f in findings):
894
+ all_term = parsed.all
895
+ if all_term is not None and all_term.qualifier in ("-", "~"):
896
+ meaning = f"Ends with {all_term.text}: {SPF_ALL_MEANINGS[all_term.qualifier]}."
897
+ elif parsed.redirect:
898
+ meaning = f"Uses {parsed.redirect}'s SPF policy (redirect)."
899
+ else:
900
+ meaning = "" # a weak or missing all has its own warning
901
+ if not complete:
902
+ counted = f"at least {counted}"
903
+ findings.insert(
904
+ 0,
905
+ Finding(
906
+ CheckStatus.PASS,
907
+ "SPF record is valid",
908
+ f"{_sentence(counted)}. {meaning}".strip(),
909
+ ),
910
+ )
911
+ return check(findings, lookups, complete)
912
+
913
+
914
+ def _spf_syntax_findings(parsed: _ParsedSpf) -> list[Finding]:
915
+ findings = []
916
+ if parsed.errors:
917
+ findings.append(
918
+ Finding(
919
+ CheckStatus.FAIL,
920
+ "SPF record has syntax errors",
921
+ f"{_sentence('; '.join(parsed.errors))}. Receivers treat the whole record as "
922
+ "invalid (permerror), so SPF fails for all of this domain's mail.",
923
+ "Correct the record. Valid terms are include, a, mx, ip4, ip6, exists, ptr, "
924
+ "all, redirect= and exp=.",
925
+ )
926
+ )
927
+ if parsed.unknown_modifiers:
928
+ findings.append(
929
+ Finding(
930
+ CheckStatus.WARN,
931
+ "Unknown SPF modifier",
932
+ f"Receivers ignore {', '.join(parsed.unknown_modifiers)}, so it has no effect.",
933
+ "Remove it, or check its spelling (the known modifiers are redirect= and exp=).",
934
+ )
935
+ )
936
+
937
+ all_term = parsed.all
938
+ if all_term is None and parsed.modifier("redirect") is None:
939
+ findings.append(
940
+ Finding(
941
+ CheckStatus.WARN,
942
+ "SPF record doesn't end with all",
943
+ "Without a final all, mail from servers the record doesn't list gets a neutral "
944
+ "result, as if there were no SPF record.",
945
+ "Add ~all (soft fail) or -all (hard fail) at the end of the record.",
946
+ )
947
+ )
948
+ elif all_term is not None:
949
+ if all_term.qualifier == "+":
950
+ findings.append(
951
+ Finding(
952
+ CheckStatus.FAIL,
953
+ f"SPF allows anyone to send ({all_term.text})",
954
+ f"{all_term.text} means {SPF_ALL_MEANINGS['+']}, so SPF gives no protection "
955
+ "against spoofing at all.",
956
+ "Change it to ~all (soft fail) or -all (hard fail).",
957
+ )
958
+ )
959
+ elif all_term.qualifier == "?":
960
+ findings.append(
961
+ Finding(
962
+ CheckStatus.WARN,
963
+ f"SPF ends with a neutral {all_term.text}",
964
+ f"With {all_term.text}, {SPF_ALL_MEANINGS['?']}.",
965
+ "Change it to ~all (soft fail) or -all (hard fail) once the record lists "
966
+ "every server that sends your mail.",
967
+ )
968
+ )
969
+ after = parsed.terms[parsed.terms.index(all_term) + 1 :]
970
+ ignored = [t.text for t in after if not (t.modifier and t.name == "exp")]
971
+ if ignored:
972
+ findings.append(
973
+ Finding(
974
+ CheckStatus.WARN,
975
+ "SPF terms after all are ignored",
976
+ f"Receivers stop at {all_term.text}, so {', '.join(ignored)} "
977
+ f"{'has' if len(ignored) == 1 else 'have'} no effect.",
978
+ f"Move {'it' if len(ignored) == 1 else 'them'} before {all_term.text}, "
979
+ "which should be the last term.",
980
+ )
981
+ )
982
+ if parsed.mechanisms("ptr"):
983
+ findings.append(
984
+ Finding(
985
+ CheckStatus.WARN,
986
+ "SPF uses the deprecated ptr mechanism",
987
+ "ptr is slow and unreliable, and some receivers ignore it, so servers it "
988
+ "is meant to allow may fail SPF.",
989
+ "Replace it with ip4/ip6 ranges or an include for the servers it covers.",
990
+ )
991
+ )
992
+ return findings
993
+
994
+
995
+ # --- DMARC ---------------------------------------------------------------------------------
996
+
997
+
998
+ def _is_dmarc(text: str) -> bool:
999
+ return re.match(r"\s*v\s*=\s*DMARC1\s*(;|$)", text, re.IGNORECASE) is not None
1000
+
1001
+
1002
+ def _parse_tags(record: str) -> tuple[list[tuple[str, str]], list[str]]:
1003
+ """`tag=value; ...` pairs (tags lower-case), and the parts that aren't tag=value."""
1004
+ tags, bad = [], []
1005
+ for part in record.split(";"):
1006
+ part = part.strip()
1007
+ if not part:
1008
+ continue
1009
+ tag, sep, value = part.partition("=")
1010
+ if not sep or not tag.strip():
1011
+ bad.append(part)
1012
+ else:
1013
+ tags.append((tag.strip().lower(), value.strip()))
1014
+ return tags, bad
1015
+
1016
+
1017
+ def _check_dmarc(domain: str, result: LookupResult, timeout: float) -> DmarcCheck:
1018
+ name = f"_dmarc.{domain}"
1019
+ records = tuple(t for t in _txt_records(result) if _is_dmarc(t))
1020
+ tags: list[tuple[str, str]] = []
1021
+
1022
+ def check(findings: list[Finding]) -> DmarcCheck:
1023
+ return DmarcCheck(name, result.status, records, tuple(tags), tuple(findings))
1024
+
1025
+ if result.status in _FAULTS:
1026
+ return check([_couldnt_check("DMARC", result, name, timeout)])
1027
+ if not records:
1028
+ return check(
1029
+ [
1030
+ Finding(
1031
+ CheckStatus.FAIL,
1032
+ "No DMARC record",
1033
+ f"There's no v=DMARC1 TXT record at {name}, so receivers have no "
1034
+ f"instructions for mail that fails SPF and DKIM, and {domain} gets no "
1035
+ "reports about who sends mail using its name. Gmail and Yahoo require "
1036
+ "DMARC from bulk senders.",
1037
+ f"Publish a TXT record at {name}, starting in monitoring mode: "
1038
+ f"v=DMARC1; p=none; rua=mailto:dmarc-reports@{domain}. Once the reports "
1039
+ "show your genuine mail passing, change p=none to quarantine, then reject.",
1040
+ )
1041
+ ]
1042
+ )
1043
+ if len(records) > 1:
1044
+ return check(
1045
+ [
1046
+ Finding(
1047
+ CheckStatus.FAIL,
1048
+ f"{len(records)} DMARC records (only one is allowed)",
1049
+ f"{name} has more than one v=DMARC1 record, so receivers ignore DMARC for "
1050
+ f"{domain} entirely.",
1051
+ "Merge them into a single record and delete the others.",
1052
+ )
1053
+ ]
1054
+ )
1055
+
1056
+ tags, bad = _parse_tags(records[0])
1057
+ values = dict(tags)
1058
+ findings = []
1059
+ errors = [f"'{part}' isn't tag=value" for part in bad]
1060
+ if tags[0][0] != "v":
1061
+ errors.append("v=DMARC1 must come first")
1062
+ policy = values.get("p", "").lower()
1063
+ if "p" not in values:
1064
+ errors.append("there's no policy (p=)")
1065
+ elif policy not in DMARC_POLICIES:
1066
+ errors.append(f"p={values['p']} isn't a policy (use none, quarantine or reject)")
1067
+ errors.extend(
1068
+ f"{tag}={values[tag]} isn't a policy"
1069
+ for tag in ("sp", "np")
1070
+ if tag in values and values[tag].lower() not in DMARC_POLICIES
1071
+ )
1072
+ pct = values.get("pct")
1073
+ if pct is not None and not (pct.isdigit() and 0 <= int(pct) <= 100):
1074
+ errors.append(f"pct={pct} isn't a number from 0 to 100")
1075
+ if errors:
1076
+ findings.append(
1077
+ Finding(
1078
+ CheckStatus.FAIL,
1079
+ "DMARC record is invalid",
1080
+ f"{_sentence('; '.join(errors))}. Receivers may ignore the record entirely.",
1081
+ "Correct the record. A minimal valid one is: v=DMARC1; p=none; "
1082
+ f"rua=mailto:dmarc-reports@{domain}",
1083
+ )
1084
+ )
1085
+ return check(findings)
1086
+
1087
+ explanation = f"p={policy}: {DMARC_POLICIES[policy]}."
1088
+ subdomains = values.get("sp", "").lower()
1089
+ if subdomains and subdomains != policy:
1090
+ explanation += f" Subdomains (sp={subdomains}): {DMARC_POLICIES[subdomains]}."
1091
+ if policy == "none":
1092
+ findings.append(
1093
+ Finding(
1094
+ CheckStatus.WARN,
1095
+ "DMARC policy is monitoring only (p=none)",
1096
+ explanation + f" Mail spoofing {domain} isn't blocked.",
1097
+ "Watch the DMARC reports until all your genuine mail passes SPF or DKIM, then "
1098
+ "change p=none to p=quarantine, and later to p=reject.",
1099
+ )
1100
+ )
1101
+ else:
1102
+ findings.append(Finding(CheckStatus.PASS, f"DMARC policy: {policy}", explanation))
1103
+ if pct is not None and int(pct) < 100:
1104
+ findings.append(
1105
+ Finding(
1106
+ CheckStatus.WARN,
1107
+ f"DMARC policy applies to only {pct}% of mail",
1108
+ f"pct={pct}: receivers apply p={policy} to {pct}% of the mail that fails "
1109
+ "DMARC and treat the rest as p=none.",
1110
+ "Raise pct to 100 (or remove it) once you're confident genuine mail passes.",
1111
+ )
1112
+ )
1113
+
1114
+ if "rua" not in values:
1115
+ findings.append(
1116
+ Finding(
1117
+ CheckStatus.WARN,
1118
+ "No DMARC report address (rua)",
1119
+ f"Without rua=, receivers don't send aggregate reports, so you can't see who "
1120
+ f"sends mail as {domain} or whether your own mail passes.",
1121
+ f"Add rua=mailto:<address>, such as a dmarc-reports@{domain} mailbox or a DMARC "
1122
+ "reporting service.",
1123
+ )
1124
+ )
1125
+ unknown = [tag for tag, _ in tags if tag not in _DMARC_TAGS]
1126
+ if unknown:
1127
+ findings.append(
1128
+ Finding(
1129
+ CheckStatus.WARN,
1130
+ "Unknown DMARC tags",
1131
+ f"Receivers ignore {', '.join(unknown)}, so "
1132
+ f"{'it has' if len(unknown) == 1 else 'they have'} no effect.",
1133
+ "Remove or correct them. Common tags are p, sp, rua, ruf, pct, adkim and aspf.",
1134
+ )
1135
+ )
1136
+ return check(findings)
1137
+
1138
+
1139
+ # --- DKIM ----------------------------------------------------------------------------------
1140
+
1141
+
1142
+ def _der_header(data: bytes, pos: int) -> tuple[int, int, int]:
1143
+ """(tag, start, end) of the DER element at `pos`."""
1144
+ tag, length = data[pos], data[pos + 1]
1145
+ pos += 2
1146
+ if length & 0x80:
1147
+ size = length & 0x7F
1148
+ length = int.from_bytes(data[pos : pos + size])
1149
+ pos += size
1150
+ if pos + length > len(data):
1151
+ raise ValueError("truncated")
1152
+ return tag, pos, pos + length
1153
+
1154
+
1155
+ def _rsa_key_bits(key: bytes) -> int | None:
1156
+ """The modulus size of a DER RSA public key (SubjectPublicKeyInfo or bare RSAPublicKey)."""
1157
+ try:
1158
+ tag, start, _ = _der_header(key, 0)
1159
+ if tag != 0x30:
1160
+ return None
1161
+ tag, start, end = _der_header(key, start)
1162
+ if tag == 0x30: # algorithm identifier: the key is in the BIT STRING after it
1163
+ tag, start, end = _der_header(key, end)
1164
+ if tag != 0x03:
1165
+ return None
1166
+ tag, start, _ = _der_header(key, start + 1) # skip the unused-bits byte
1167
+ if tag != 0x30:
1168
+ return None
1169
+ tag, start, end = _der_header(key, start)
1170
+ if tag != 0x02:
1171
+ return None
1172
+ return int.from_bytes(key[start:end]).bit_length()
1173
+ except (IndexError, ValueError):
1174
+ return None
1175
+
1176
+
1177
+ def _is_dkim(text: str) -> bool:
1178
+ tags, _ = _parse_tags(text)
1179
+ values = dict(tags)
1180
+ return "p" in values and values.get("v", "DKIM1") == "DKIM1"
1181
+
1182
+
1183
+ def _dkim_selector(selector: str, name: str, result: LookupResult, custom: bool) -> DkimSelector:
1184
+ record = next((t for t in _txt_records(result) if _is_dkim(t)), None)
1185
+ if record is None:
1186
+ return DkimSelector(selector, name, result.status, None, custom)
1187
+
1188
+ values = dict(_parse_tags(record)[0])
1189
+ key_type = values.get("k", "rsa").lower()
1190
+ key_text = re.sub(r"\s+", "", values["p"])
1191
+ if not key_text:
1192
+ return DkimSelector(selector, name, result.status, record, custom, key_type, revoked=True)
1193
+ try:
1194
+ key = base64.b64decode(key_text, validate=True)
1195
+ except (binascii.Error, ValueError):
1196
+ key = b""
1197
+ bits = _rsa_key_bits(key) if key_type == "rsa" else None
1198
+ # An RSA key must parse; an Ed25519 key is exactly 32 bytes.
1199
+ malformed = bits is None if key_type == "rsa" else key_type == "ed25519" and len(key) != 32
1200
+ return DkimSelector(
1201
+ selector,
1202
+ name,
1203
+ result.status,
1204
+ record,
1205
+ custom,
1206
+ key_type=key_type,
1207
+ key_bits=bits,
1208
+ malformed=malformed,
1209
+ )
1210
+
1211
+
1212
+ def describe_key(selector: DkimSelector) -> str:
1213
+ """The key's type and size for display, e.g. "RSA 2048-bit" or "Ed25519"."""
1214
+ if selector.key_bits is not None:
1215
+ return f"RSA {selector.key_bits}-bit"
1216
+ if selector.key_type == "ed25519":
1217
+ return "Ed25519"
1218
+ return (selector.key_type or "rsa").upper()
1219
+
1220
+
1221
+ def _check_dkim(
1222
+ domain: str,
1223
+ selectors: list[str],
1224
+ custom: set[str],
1225
+ results: list[LookupResult],
1226
+ timeout: float,
1227
+ sends_mail: bool = True,
1228
+ ) -> DkimCheck:
1229
+ checked = tuple(
1230
+ _dkim_selector(s, f"{s}._domainkey.{domain}", r, s in custom)
1231
+ for s, r in zip(selectors, results, strict=True)
1232
+ )
1233
+ findings = []
1234
+ usable = [s for s in checked if s.found and not s.revoked and not s.malformed]
1235
+
1236
+ for s, result in zip(checked, results, strict=True):
1237
+ if s.malformed:
1238
+ findings.append(
1239
+ Finding(
1240
+ CheckStatus.FAIL,
1241
+ f"DKIM key at {s.selector} is malformed",
1242
+ f"The p= value at {s.name} isn't a valid {describe_key(s)} public key, so "
1243
+ "receivers can't verify mail signed with this selector.",
1244
+ "Copy the DKIM record again from your email provider, making sure the "
1245
+ "whole key was pasted in (long keys are often cut off).",
1246
+ )
1247
+ )
1248
+ elif s.key_bits is not None and s.key_bits < 1024:
1249
+ findings.append(
1250
+ Finding(
1251
+ CheckStatus.FAIL,
1252
+ f"DKIM key at {s.selector} is too short ({s.key_bits}-bit)",
1253
+ "Receivers such as Gmail treat signatures from keys under 1024 bits as "
1254
+ "invalid, and short keys can be cracked.",
1255
+ "Generate a new 2048-bit key in your email provider's settings and publish it.",
1256
+ )
1257
+ )
1258
+ elif s.key_bits is not None and s.key_bits < 2048:
1259
+ findings.append(
1260
+ Finding(
1261
+ CheckStatus.WARN,
1262
+ f"DKIM key at {s.selector} is {s.key_bits}-bit",
1263
+ f"{s.key_bits}-bit keys still work, but 2048 bits is the recommended minimum.",
1264
+ "Generate a 2048-bit key in your email provider's settings, publish it "
1265
+ "under a new selector, and switch signing to it.",
1266
+ )
1267
+ )
1268
+ if s.custom and not s.found:
1269
+ if s.lookup_status in _FAULTS:
1270
+ findings.append(
1271
+ _couldnt_check(f"DKIM selector {s.selector}", result, s.name, timeout)
1272
+ )
1273
+ else:
1274
+ findings.append(
1275
+ Finding(
1276
+ CheckStatus.FAIL,
1277
+ f"No DKIM key at selector {s.selector}",
1278
+ f"There's no DKIM key record at {s.name}, so receivers can't verify "
1279
+ f"mail signed with selector {s.selector}.",
1280
+ "Check the selector (the s= value in an email's DKIM-Signature header), "
1281
+ "and publish the DKIM record your email provider gives you.",
1282
+ )
1283
+ )
1284
+
1285
+ if usable:
1286
+ names = ", ".join(f"{s.selector} ({describe_key(s)})" for s in usable)
1287
+ findings.insert(
1288
+ 0,
1289
+ Finding(
1290
+ CheckStatus.PASS,
1291
+ f"DKIM {'key' if len(usable) == 1 else 'keys'} found",
1292
+ f"Selector {names}. Receivers can use "
1293
+ f"{'this key' if len(usable) == 1 else 'these keys'} to verify that mail "
1294
+ f"signed by {domain} hasn't been forged or altered.",
1295
+ ),
1296
+ )
1297
+ else:
1298
+ revoked = [s.selector for s in checked if s.revoked]
1299
+ # A custom selector's failure was reported above.
1300
+ faults = [
1301
+ (s, r)
1302
+ for s, r in zip(checked, results, strict=True)
1303
+ if r.status in _FAULTS and not s.custom
1304
+ ]
1305
+ if faults and not any(s.found for s in checked):
1306
+ s, result = faults[0]
1307
+ findings.append(_couldnt_check("DKIM", result, s.name, timeout))
1308
+ elif not sends_mail and not any(s.malformed for s in checked):
1309
+ note = " The empty (revoked) keys published for it say the same." if revoked else ""
1310
+ findings.append(
1311
+ Finding(
1312
+ CheckStatus.PASS,
1313
+ "No DKIM key needed",
1314
+ f"{domain}'s SPF record (v=spf1 -all) says it sends no mail, so there's "
1315
+ f"nothing to sign.{note}",
1316
+ )
1317
+ )
1318
+ elif revoked and not any(f.status is CheckStatus.FAIL for f in findings):
1319
+ one = len(revoked) == 1
1320
+ findings.append(
1321
+ Finding(
1322
+ CheckStatus.WARN,
1323
+ f"DKIM {'key' if one else 'keys'} revoked",
1324
+ f"The {'key' if one else 'keys'} at {', '.join(revoked)} "
1325
+ f"{'has' if one else 'have'} an empty p=, meaning "
1326
+ f"{'it has' if one else 'they have'} been withdrawn. Mail signed with "
1327
+ f"{'it' if one else 'them'} fails DKIM.",
1328
+ "If mail is still signed with these selectors, publish current keys for "
1329
+ "them; otherwise check which selector your provider signs with now.",
1330
+ )
1331
+ )
1332
+ elif not any(s.found for s in checked) and not custom:
1333
+ findings.append(
1334
+ Finding(
1335
+ CheckStatus.WARN,
1336
+ "No DKIM key at the common selectors",
1337
+ f"None of the selectors tried ({', '.join(selectors)}) has a DKIM key. "
1338
+ f"{domain} may still use DKIM under another selector: DNS has no way to "
1339
+ "list them.",
1340
+ "Open an email sent from this domain, find the s= value in its "
1341
+ "DKIM-Signature header, and check that selector with --selector. If DKIM "
1342
+ "isn't set up, turn it on in your email provider's settings and publish "
1343
+ "the record it gives you.",
1344
+ )
1345
+ )
1346
+ return DkimCheck(checked, tuple(findings))