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/dnssec.py ADDED
@@ -0,0 +1,767 @@
1
+ """Is a domain signed with DNSSEC, and does its chain of trust validate from the root down?
2
+
3
+ The records are fetched through a resolver (with the DO bit for signatures and CD so a
4
+ validating resolver hands over broken data instead of SERVFAIL), then checked here:
5
+
6
+ - the root's keys against the built-in root trust anchors (IANA's KSK-2017 and KSK-2024);
7
+ - for each zone below: the parent's signed DS record, which must match one of the zone's
8
+ DNSKEYs, which must sign the zone's key set;
9
+ - finally the zone's SOA and the name's A records, signed with the zone's keys.
10
+
11
+ Signatures are only valid between two dates, so a wrong system clock breaks validation;
12
+ the root zone's SOA serial (YYYYMMDDnn) shows roughly what today's date is.
13
+ """
14
+
15
+ import ipaddress
16
+ import time
17
+ from collections.abc import Iterable, Sequence
18
+ from concurrent.futures import ThreadPoolExecutor
19
+ from dataclasses import dataclass, replace
20
+ from datetime import UTC, datetime
21
+ from enum import StrEnum
22
+ from typing import TypeVar
23
+
24
+ import dns.dnssec
25
+ import dns.exception
26
+ import dns.flags
27
+ import dns.message
28
+ import dns.name
29
+ import dns.query
30
+ import dns.rcode
31
+ import dns.rdata
32
+ import dns.rdataclass
33
+ import dns.rdatatype
34
+ import dns.rrset
35
+ from dns.rdtypes.ANY.DNSKEY import DNSKEY
36
+ from dns.rdtypes.ANY.DS import DS
37
+
38
+ from dnskit.core.diagnosis import Diagnosis
39
+ from dnskit.core.lookup import _choose_nameservers
40
+ from dnskit.core.nameservers import ResolverChoice
41
+ from dnskit.core.outside import DnsBlocking, blocked_diagnosis, check_blocking
42
+ from dnskit.core.reach import parse_target
43
+
44
+ _R = TypeVar("_R", bound=dns.rdata.Rdata)
45
+
46
+ # The root zone's trust anchors (https://data.iana.org/root-anchors/root-anchors.xml).
47
+ ROOT_TRUST_ANCHORS: tuple[str, ...] = (
48
+ "20326 8 2 E06D44B80B8F1D39A95C0B0D7C65D08458E880409BBC683457104237C7F8EC8D", # KSK-2017
49
+ "38696 8 2 683D2D0ACB8C9B712A1948B27F741219298D0A450D612C483AF444A4C0FB2B16", # KSK-2024
50
+ )
51
+
52
+ # The root zone is re-published twice a day and its SOA cached for up to a day, so its
53
+ # serial's date trails the real date by up to about two days.
54
+ # Public resolvers that pass DNSSEC signatures along, used when this computer's DNS
55
+ # server strips them.
56
+ DNSSEC_FALLBACKS: tuple[str, ...] = ("8.8.8.8", "1.1.1.1")
57
+ CLOCK_BEHIND_DAYS = 1.5 # local clock this far before the root zone's date: wrong
58
+ CLOCK_AHEAD_DAYS = 3.0 # local clock this far after it: wrong
59
+
60
+ _ROOT = dns.name.root
61
+ _SEP_FLAG = 0x0001 # DNSKEY flag marking a key-signing key
62
+
63
+
64
+ class ZoneStatus(StrEnum):
65
+ SECURE = "secure" # this link in the chain validates
66
+ UNSIGNED = "unsigned" # no DS at the parent: DNSSEC isn't on from here down
67
+ BOGUS = "bogus" # signed, but something doesn't check out
68
+ UNKNOWN = "unknown" # the data couldn't be fetched
69
+
70
+
71
+ class DnssecStatus(StrEnum):
72
+ SECURE = "secure" # the whole chain validates
73
+ INSECURE = "insecure" # DNSSEC isn't enabled for the domain (or a zone above it)
74
+ BOGUS = "bogus" # DNSSEC is enabled but broken: validating resolvers will fail it
75
+ UNKNOWN = "unknown" # couldn't be checked
76
+
77
+
78
+ class BogusKind(StrEnum):
79
+ NO_DNSKEY = "no_dnskey" # DS at the parent, but the zone has no keys
80
+ DS_MISMATCH = "ds_mismatch" # no key matches the parent's DS
81
+ BAD_SIGNATURE = "bad_signature" # a signature doesn't verify
82
+ EXPIRED = "expired" # a signature is outside its validity dates
83
+ MISSING_SIGNATURE = "missing_signature" # records that should be signed aren't
84
+
85
+
86
+ class ClockState(StrEnum):
87
+ OK = "ok"
88
+ WRONG = "wrong"
89
+ UNKNOWN = "unknown"
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class DsInfo:
94
+ key_tag: int
95
+ algorithm: str # e.g. "ECDSAP256SHA256"
96
+ digest_type: int # 2 = SHA-256
97
+
98
+
99
+ @dataclass(frozen=True)
100
+ class KeyInfo:
101
+ key_tag: int
102
+ algorithm: str
103
+ ksk: bool # key-signing key (SEP flag); otherwise a zone-signing key
104
+
105
+
106
+ @dataclass(frozen=True)
107
+ class ZoneCheck:
108
+ zone: str # with the trailing dot; "." is the root
109
+ status: ZoneStatus
110
+ ds: tuple[DsInfo, ...] = () # the parent's DS records (the trust anchors for the root)
111
+ keys: tuple[KeyInfo, ...] = () # the zone's DNSKEYs
112
+ summary: str = ""
113
+ kind: BogusKind | None = None # BOGUS: what's wrong
114
+
115
+
116
+ @dataclass(frozen=True)
117
+ class RecordCheck:
118
+ name: str
119
+ rtype: str
120
+ status: ZoneStatus
121
+ summary: str
122
+ kind: BogusKind | None = None
123
+
124
+
125
+ @dataclass(frozen=True)
126
+ class ClockCheck:
127
+ state: ClockState
128
+ local: datetime # this computer's clock, UTC
129
+ reference: datetime | None # the root zone's date (from its SOA serial)
130
+ summary: str
131
+
132
+
133
+ @dataclass(frozen=True)
134
+ class DnssecReport:
135
+ name: str # without the trailing dot
136
+ zones: tuple[ZoneCheck, ...] # root first
137
+ records: tuple[RecordCheck, ...] # the zone's SOA, the name's A records
138
+ clock: ClockCheck
139
+ nameserver: str
140
+ nameserver_source: str
141
+ elapsed_ms: float
142
+ resolver_choice: ResolverChoice | None = None
143
+ name_missing: bool = False # the name itself doesn't exist (NXDOMAIN)
144
+ error: str = "" # why it couldn't be checked at all
145
+ signatures_stripped: bool = False # the resolver answered, but without DNSSEC signatures
146
+ # This computer's DNS server, when it strips signatures and DNSSEC_FALLBACKS were tried:
147
+ # `nameserver` is then the fallback that worked, or still this server if none did.
148
+ stripped_by: str | None = None
149
+ blocking: DnsBlocking | None = None # set when an outside --server didn't answer
150
+
151
+ @property
152
+ def status(self) -> DnssecStatus:
153
+ statuses = [z.status for z in self.zones] + [r.status for r in self.records]
154
+ if self.error or not self.zones:
155
+ return DnssecStatus.UNKNOWN
156
+ if ZoneStatus.BOGUS in statuses:
157
+ return DnssecStatus.BOGUS
158
+ if ZoneStatus.UNKNOWN in statuses:
159
+ return DnssecStatus.UNKNOWN
160
+ if ZoneStatus.UNSIGNED in statuses:
161
+ return DnssecStatus.INSECURE
162
+ return DnssecStatus.SECURE
163
+
164
+ @property
165
+ def zone(self) -> str:
166
+ """The deepest zone checked: the domain's own zone, or where the chain stopped."""
167
+ return self.zones[-1].zone if self.zones else "."
168
+
169
+ @property
170
+ def problem(self) -> ZoneCheck | RecordCheck | None:
171
+ """The first link that isn't secure."""
172
+ checks: list[ZoneCheck | RecordCheck] = [*self.zones, *self.records]
173
+ return next((c for c in checks if c.status is not ZoneStatus.SECURE), None)
174
+
175
+
176
+ def dnssec_check(
177
+ target: str, nameserver: str | None = None, timeout: float = 5.0, refresh: bool = False
178
+ ) -> DnssecReport:
179
+ """Check `target`'s DNSSEC chain of trust. An invalid name raises ValueError.
180
+
181
+ Records come from `nameserver`, or the chosen system nameserver as in `lookup()`. When
182
+ that system nameserver strips DNSSEC signatures (some routers and filters do), the check
183
+ is redone through the first of DNSSEC_FALLBACKS that works, and `stripped_by` names it.
184
+ An explicit `nameserver` is never replaced.
185
+ """
186
+ name = parse_target(target)
187
+ report = _check_through(name, nameserver, timeout, refresh)
188
+ if nameserver is not None or not report.signatures_stripped:
189
+ return report
190
+ with ThreadPoolExecutor(max_workers=len(DNSSEC_FALLBACKS)) as pool:
191
+ retries = list(
192
+ pool.map(
193
+ lambda ns: _check_through(name, ns, timeout, False, diagnose=False),
194
+ DNSSEC_FALLBACKS,
195
+ )
196
+ )
197
+ stripped_by = report.nameserver
198
+ usable = next((r for r in retries if not r.error), None)
199
+ if usable is None:
200
+ return replace(report, stripped_by=stripped_by)
201
+ return replace(
202
+ usable,
203
+ stripped_by=stripped_by,
204
+ nameserver_source=f"this computer's DNS server {stripped_by} strips DNSSEC signatures",
205
+ resolver_choice=report.resolver_choice,
206
+ elapsed_ms=report.elapsed_ms + max(r.elapsed_ms for r in retries),
207
+ )
208
+
209
+
210
+ def _check_through(
211
+ name: str, nameserver: str | None, timeout: float, refresh: bool, diagnose: bool = True
212
+ ) -> DnssecReport:
213
+ """The check through one nameserver (or the chosen system one), with no fallback.
214
+
215
+ Without `diagnose`, no reply doesn't run `check_blocking` (for fallback attempts).
216
+ """
217
+ qname = dns.name.from_text(name)
218
+ start = time.perf_counter()
219
+ selection = _choose_nameservers(nameserver, refresh)
220
+ servers = selection.nameservers
221
+
222
+ def report(**fields: object) -> DnssecReport:
223
+ base: dict[str, object] = {
224
+ "name": name,
225
+ "zones": (),
226
+ "records": (),
227
+ "nameserver": servers[0],
228
+ "nameserver_source": selection.source,
229
+ "elapsed_ms": (time.perf_counter() - start) * 1000,
230
+ "resolver_choice": selection.choice,
231
+ }
232
+ return DnssecReport(**(base | fields)) # type: ignore[arg-type]
233
+
234
+ suffixes = [qname.split(depth)[1] for depth in range(2, len(qname) + 1)]
235
+ queries = [(_ROOT, "DNSKEY"), (_ROOT, "SOA")]
236
+ queries += [(s, rtype) for s in suffixes for rtype in ("NS", "DS", "DNSKEY")]
237
+ queries += [(qname, "A")]
238
+ with ThreadPoolExecutor(max_workers=min(len(queries), 16)) as pool:
239
+ fetched = dict(
240
+ zip(
241
+ queries,
242
+ pool.map(lambda q: _fetch(q[0], q[1], servers, timeout), queries),
243
+ strict=True,
244
+ )
245
+ )
246
+
247
+ root_keys, root_soa = fetched[(_ROOT, "DNSKEY")], fetched[(_ROOT, "SOA")]
248
+ clock = check_clock(root_soa, root_keys)
249
+ if root_keys.rcode is None:
250
+ return report(
251
+ clock=clock,
252
+ error=f"no response from {servers[0]} ({root_keys.error})",
253
+ blocking=_blocking_for(nameserver) if diagnose else None,
254
+ )
255
+ if root_keys.rrset is None or root_keys.rrsig is None:
256
+ return report(
257
+ clock=clock,
258
+ error=f"{servers[0]} doesn't return DNSSEC signatures, so nothing can be "
259
+ "checked through it (some routers and DNS filters strip them)",
260
+ signatures_stripped=True,
261
+ )
262
+
263
+ now = time.time()
264
+ zones = [_check_root(root_keys, now)]
265
+ parent_keys = root_keys.rrset
266
+ name_missing = False
267
+ for suffix in suffixes:
268
+ if zones[-1].status is not ZoneStatus.SECURE:
269
+ break
270
+ ns, ds, keys = (fetched[(suffix, t)] for t in ("NS", "DS", "DNSKEY"))
271
+ if ns.rcode == "NXDOMAIN":
272
+ name_missing = True
273
+ break
274
+ if ns.cname or (ns.rrset is None and ds.rrset is None):
275
+ continue # not a zone of its own (or an alias): part of its parent zone
276
+ zone = _check_zone(suffix, ds, keys, parent_keys, now)
277
+ zones.append(zone)
278
+ if zone.status is ZoneStatus.SECURE and keys.rrset is not None:
279
+ parent_keys = keys.rrset
280
+
281
+ records: list[RecordCheck] = []
282
+ if zones[-1].status is ZoneStatus.SECURE:
283
+ zone_name = dns.name.from_text(zones[-1].zone)
284
+ soa = _fetch(zone_name, "SOA", servers, timeout)
285
+ records.append(_check_records(zone_name, "SOA", soa, parent_keys, now))
286
+ a = fetched[(qname, "A")]
287
+ if a.rrset is not None and not a.cname:
288
+ records.append(_check_records(qname, "A", a, parent_keys, now))
289
+ return report(
290
+ zones=tuple(zones), records=tuple(records), clock=clock, name_missing=name_missing
291
+ )
292
+
293
+
294
+ def _blocking_for(nameserver: str | None) -> DnsBlocking | None:
295
+ """When an explicit internet --server didn't answer, find out whether DNS is blocked."""
296
+ if nameserver is None:
297
+ return check_blocking() # the system's own servers failed: maybe offline
298
+ try:
299
+ public = ipaddress.ip_address(nameserver).is_global
300
+ except ValueError:
301
+ return None
302
+ return check_blocking() if public else None
303
+
304
+
305
+ # --- Fetching -----------------------------------------------------------------------------
306
+
307
+
308
+ @dataclass(frozen=True)
309
+ class Fetched:
310
+ rcode: str | None # None when no server responded
311
+ rrset: dns.rrset.RRset | None = None # the records of the asked type at the name
312
+ rrsig: dns.rrset.RRset | None = None # their signatures
313
+ cname: bool = False # the name is an alias
314
+ error: str = ""
315
+
316
+
317
+ def _send(query: dns.message.Message, address: str, timeout: float) -> dns.message.Message:
318
+ response, _ = dns.query.udp_with_fallback(query, address, timeout=timeout)
319
+ return response
320
+
321
+
322
+ def _fetch(name: dns.name.Name, rtype: str, nameservers: Sequence[str], timeout: float) -> Fetched:
323
+ """Ask the first nameserver that responds, with signatures and checking disabled."""
324
+ query = dns.message.make_query(name, rtype, want_dnssec=True, use_edns=0, payload=1232)
325
+ query.flags |= dns.flags.CD
326
+ error = "no nameserver"
327
+ for nameserver in nameservers:
328
+ try:
329
+ response = _send(query, nameserver, timeout)
330
+ except dns.exception.Timeout:
331
+ error = "timed out"
332
+ continue
333
+ except (OSError, dns.exception.DNSException) as exc:
334
+ error = str(exc) or type(exc).__name__
335
+ continue
336
+ return _parse(response, name, dns.rdatatype.from_text(rtype))
337
+ return Fetched(None, error=error)
338
+
339
+
340
+ def _parse(
341
+ response: dns.message.Message, name: dns.name.Name, rdtype: dns.rdatatype.RdataType
342
+ ) -> Fetched:
343
+ rrset = rrsig = None
344
+ cname = False
345
+ for found in response.answer:
346
+ if found.name != name:
347
+ continue
348
+ if found.rdtype == rdtype:
349
+ rrset = found
350
+ elif found.rdtype == dns.rdatatype.RRSIG and found.covers == rdtype:
351
+ rrsig = found
352
+ elif found.rdtype == dns.rdatatype.CNAME:
353
+ cname = True
354
+ return Fetched(dns.rcode.to_text(response.rcode()), rrset, rrsig, cname)
355
+
356
+
357
+ # --- Validating ---------------------------------------------------------------------------
358
+
359
+
360
+ def _anchors() -> list[dns.rdata.Rdata]:
361
+ return [
362
+ dns.rdata.from_text(dns.rdataclass.IN, dns.rdatatype.DS, text)
363
+ for text in ROOT_TRUST_ANCHORS
364
+ ]
365
+
366
+
367
+ def _check_root(keys: Fetched, now: float) -> ZoneCheck:
368
+ assert keys.rrset is not None and keys.rrsig is not None
369
+ anchors = _anchors()
370
+ info = _key_info(keys.rrset)
371
+ ds = tuple(_ds_info(a) for a in anchors)
372
+ matched = _matching_keys(_ROOT, keys.rrset, anchors)
373
+ if not matched:
374
+ return ZoneCheck(
375
+ ".",
376
+ ZoneStatus.BOGUS,
377
+ ds,
378
+ info,
379
+ "none of the root's keys match the built-in trust anchors",
380
+ BogusKind.DS_MISMATCH,
381
+ )
382
+ error = _verify(keys.rrset, keys.rrsig, matched, now)
383
+ if error:
384
+ return ZoneCheck(
385
+ ".", ZoneStatus.BOGUS, ds, info, f"root key set: {error}", _error_kind(error)
386
+ )
387
+ tags = ", ".join(str(dns.dnssec.key_id(k)) for k in matched)
388
+ return ZoneCheck(".", ZoneStatus.SECURE, ds, info, f"keys signed by trust anchor {tags}")
389
+
390
+
391
+ def _check_zone(
392
+ zone: dns.name.Name,
393
+ ds: Fetched,
394
+ keys: Fetched,
395
+ parent_keys: dns.rrset.RRset,
396
+ now: float,
397
+ ) -> ZoneCheck:
398
+ text = zone.to_text()
399
+ parent = zone.parent().to_text()
400
+ info = _key_info(keys.rrset) if keys.rrset is not None else ()
401
+ if ds.rcode is None or (keys.rcode is None and ds.rrset is not None):
402
+ error = ds.error or keys.error
403
+ return ZoneCheck(text, ZoneStatus.UNKNOWN, keys=info, summary=f"couldn't fetch: {error}")
404
+ if ds.rrset is None:
405
+ summary = f"no DS record at {parent}: not signed"
406
+ if info:
407
+ summary = f"has keys, but no DS record at {parent}: the chain stops here"
408
+ return ZoneCheck(text, ZoneStatus.UNSIGNED, keys=info, summary=summary)
409
+
410
+ ds_info = tuple(_ds_info(d) for d in ds.rrset)
411
+ if ds.rrsig is None:
412
+ return ZoneCheck(
413
+ text,
414
+ ZoneStatus.BOGUS,
415
+ ds_info,
416
+ info,
417
+ f"the DS record at {parent} isn't signed",
418
+ BogusKind.MISSING_SIGNATURE,
419
+ )
420
+ error = _verify(ds.rrset, ds.rrsig, parent_keys, now)
421
+ if error:
422
+ return ZoneCheck(
423
+ text,
424
+ ZoneStatus.BOGUS,
425
+ ds_info,
426
+ info,
427
+ f"DS record at {parent}: {error}",
428
+ _error_kind(error),
429
+ )
430
+ if keys.rrset is None:
431
+ return ZoneCheck(
432
+ text,
433
+ ZoneStatus.BOGUS,
434
+ ds_info,
435
+ info,
436
+ f"{parent} has a DS record for it, but the zone has no DNSKEY records",
437
+ BogusKind.NO_DNSKEY,
438
+ )
439
+ matched = _matching_keys(zone, keys.rrset, list(ds.rrset))
440
+ if not matched:
441
+ ds_tags = ", ".join(str(d.key_tag) for d in ds_info)
442
+ key_tags = ", ".join(str(k.key_tag) for k in info if k.ksk) or "none"
443
+ return ZoneCheck(
444
+ text,
445
+ ZoneStatus.BOGUS,
446
+ ds_info,
447
+ info,
448
+ f"the DS record at {parent} (key {ds_tags}) matches none of its keys "
449
+ f"(key-signing keys: {key_tags})",
450
+ BogusKind.DS_MISMATCH,
451
+ )
452
+ if keys.rrsig is None:
453
+ return ZoneCheck(
454
+ text,
455
+ ZoneStatus.BOGUS,
456
+ ds_info,
457
+ info,
458
+ "its DNSKEY records aren't signed",
459
+ BogusKind.MISSING_SIGNATURE,
460
+ )
461
+ error = _verify(keys.rrset, keys.rrsig, matched, now)
462
+ if error:
463
+ return ZoneCheck(
464
+ text, ZoneStatus.BOGUS, ds_info, info, f"key set: {error}", _error_kind(error)
465
+ )
466
+ tags = ", ".join(str(dns.dnssec.key_id(k)) for k in matched)
467
+ return ZoneCheck(
468
+ text, ZoneStatus.SECURE, ds_info, info, f"DS at {parent} matches key {tags}; keys signed"
469
+ )
470
+
471
+
472
+ def _check_records(
473
+ name: dns.name.Name, rtype: str, fetched: Fetched, keys: dns.rrset.RRset, now: float
474
+ ) -> RecordCheck:
475
+ text = name.to_text()
476
+ if fetched.rrset is None:
477
+ reason = fetched.error or f"no {rtype} record"
478
+ return RecordCheck(text, rtype, ZoneStatus.UNKNOWN, f"couldn't fetch ({reason})")
479
+ if fetched.rrsig is None:
480
+ return RecordCheck(text, rtype, ZoneStatus.BOGUS, "not signed", BogusKind.MISSING_SIGNATURE)
481
+ error = _verify(fetched.rrset, fetched.rrsig, keys, now)
482
+ if error:
483
+ return RecordCheck(text, rtype, ZoneStatus.BOGUS, error, _error_kind(error))
484
+ signer = fetched.rrsig[0]
485
+ expires = datetime.fromtimestamp(signer.expiration, UTC).strftime("%Y-%m-%d")
486
+ return RecordCheck(
487
+ text, rtype, ZoneStatus.SECURE, f"signed by key {signer.key_tag}, valid until {expires}"
488
+ )
489
+
490
+
491
+ def _verify(
492
+ rrset: dns.rrset.RRset,
493
+ rrsig: dns.rrset.RRset,
494
+ keys: dns.rrset.RRset | Sequence[dns.rdata.Rdata],
495
+ now: float,
496
+ ) -> str:
497
+ """ "" if one of the signatures verifies with `keys`; otherwise why not."""
498
+ if not isinstance(keys, dns.rrset.RRset): # some of a zone's own keys
499
+ keys = dns.rrset.from_rdata_list(rrset.name, 0, list(keys))
500
+ try:
501
+ dns.dnssec.validate(rrset, rrsig, {keys.name: keys}, now=now)
502
+ except dns.exception.ValidationFailure as exc:
503
+ return _describe_failure(rrsig, now, str(exc))
504
+ except dns.exception.DNSException as exc: # e.g. an unsupported algorithm
505
+ return str(exc) or type(exc).__name__
506
+ return ""
507
+
508
+
509
+ def _describe_failure(rrsig: dns.rrset.RRset, now: float, error: str) -> str:
510
+ """Say plainly when the signatures are expired or not yet valid."""
511
+ if all(sig.expiration < now for sig in rrsig):
512
+ date = datetime.fromtimestamp(max(s.expiration for s in rrsig), UTC)
513
+ return f"signature expired on {date:%Y-%m-%d}"
514
+ if all(sig.inception > now for sig in rrsig):
515
+ date = datetime.fromtimestamp(min(s.inception for s in rrsig), UTC)
516
+ return f"signature not valid until {date:%Y-%m-%d}"
517
+ return "signature doesn't verify" if "verify" in error.lower() or not error else error
518
+
519
+
520
+ def _error_kind(error: str) -> BogusKind:
521
+ if error.startswith(("signature expired", "signature not valid until")):
522
+ return BogusKind.EXPIRED
523
+ return BogusKind.BAD_SIGNATURE
524
+
525
+
526
+ def _matching_keys(
527
+ zone: dns.name.Name, keys: dns.rrset.RRset, ds_records: Sequence[dns.rdata.Rdata]
528
+ ) -> list[DNSKEY]:
529
+ """The DNSKEYs that one of `ds_records` vouches for."""
530
+ matched: list[DNSKEY] = []
531
+ for key in _as(DNSKEY, keys):
532
+ for ds in _as(DS, ds_records):
533
+ try:
534
+ made = dns.dnssec.make_ds(zone, key, ds.digest_type, validating=True)
535
+ except (dns.exception.UnsupportedAlgorithm, dns.exception.DNSException):
536
+ continue
537
+ if made == ds:
538
+ matched.append(key)
539
+ break
540
+ return matched
541
+
542
+
543
+ def _key_info(keys: dns.rrset.RRset) -> tuple[KeyInfo, ...]:
544
+ return tuple(
545
+ KeyInfo(
546
+ dns.dnssec.key_id(key),
547
+ dns.dnssec.algorithm_to_text(key.algorithm),
548
+ bool(key.flags & _SEP_FLAG),
549
+ )
550
+ for key in keys
551
+ )
552
+
553
+
554
+ def _ds_info(ds: dns.rdata.Rdata) -> DsInfo:
555
+ (record,) = _as(DS, [ds])
556
+ return DsInfo(
557
+ record.key_tag, dns.dnssec.algorithm_to_text(record.algorithm), record.digest_type
558
+ )
559
+
560
+
561
+ def _as(kind: type[_R], records: Iterable[dns.rdata.Rdata]) -> list[_R]:
562
+ """The records as their specific type, for the type checker (rdatasets hold Rdata)."""
563
+ return [r for r in records if isinstance(r, kind)]
564
+
565
+
566
+ # --- Clock --------------------------------------------------------------------------------
567
+
568
+
569
+ def check_clock(soa: Fetched, keys: Fetched, now: datetime | None = None) -> ClockCheck:
570
+ """Compare this computer's clock with the root zone's date and signature dates."""
571
+ local = now or datetime.now(UTC)
572
+ reference = _serial_date(soa)
573
+ if keys.rrsig is not None:
574
+ stamp = local.timestamp()
575
+ if all(sig.inception > stamp or sig.expiration < stamp for sig in keys.rrsig):
576
+ return ClockCheck(
577
+ ClockState.WRONG,
578
+ local,
579
+ reference,
580
+ f"wrong: {local:%Y-%m-%d} is outside the root signatures' validity dates",
581
+ )
582
+ if reference is None:
583
+ return ClockCheck(ClockState.UNKNOWN, local, None, "couldn't check (no root zone date)")
584
+ days = (local - reference).total_seconds() / 86400
585
+ if days < -CLOCK_BEHIND_DAYS or days > CLOCK_AHEAD_DAYS:
586
+ direction = "behind" if days < 0 else "ahead of"
587
+ return ClockCheck(
588
+ ClockState.WRONG,
589
+ local,
590
+ reference,
591
+ f"wrong: {local:%Y-%m-%d}, about {abs(days):.0f} days {direction} the root zone "
592
+ f"({reference:%Y-%m-%d})",
593
+ )
594
+ return ClockCheck(
595
+ ClockState.OK, local, reference, f"looks right (root zone from {reference:%Y-%m-%d})"
596
+ )
597
+
598
+
599
+ def _serial_date(soa: Fetched) -> datetime | None:
600
+ """The date in the root zone's SOA serial, which is YYYYMMDDnn."""
601
+ if soa.rrset is None:
602
+ return None
603
+ try:
604
+ return datetime.strptime(str(soa.rrset[0].serial)[:8], "%Y%m%d").replace(tzinfo=UTC)
605
+ except (ValueError, AttributeError):
606
+ return None
607
+
608
+
609
+ # --- Explanation --------------------------------------------------------------------------
610
+
611
+ PROTECTS = (
612
+ "DNSSEC protects against forged DNS answers: someone on the network, or a poisoned "
613
+ "resolver cache, can't send visitors to a fake address without the signature check "
614
+ "failing. It doesn't encrypt DNS or hide which sites you visit."
615
+ )
616
+
617
+
618
+ def explain_dnssec(report: DnssecReport) -> Diagnosis:
619
+ """The result in plain English, with what DNSSEC is for and what to do next."""
620
+ zone = report.zone.rstrip(".") or "the root"
621
+ name = report.name
622
+ if report.name_missing and report.status is DnssecStatus.SECURE:
623
+ return Diagnosis(
624
+ title=f"{name} doesn't exist",
625
+ explanation=f"The chain of trust validates down to {zone}, which says {name} "
626
+ "doesn't exist (NXDOMAIN), so there are no records of its own to check.",
627
+ suggestion="Check the spelling, or check a name that has records.",
628
+ )
629
+ match report.status:
630
+ case DnssecStatus.SECURE:
631
+ return Diagnosis(
632
+ title=f"DNSSEC is on and validates for {name}",
633
+ explanation=f"Every link from the root down to {zone} is signed and checks "
634
+ "out: each parent vouches for its child's key with a DS record, and each zone "
635
+ f"signs its records with that key. {PROTECTS} Validating resolvers (such as "
636
+ "8.8.8.8, 1.1.1.1 and 9.9.9.9) check this automatically.",
637
+ suggestion="Nothing to do. When you change DNS host or keys, update the DS "
638
+ "record at the registrar at the same time, or validation breaks.",
639
+ )
640
+ case DnssecStatus.INSECURE:
641
+ return _insecure(report)
642
+ case DnssecStatus.BOGUS:
643
+ return _bogus(report)
644
+ if report.blocking is not None:
645
+ return blocked_diagnosis(report.blocking, report.nameserver, one=True)
646
+ if report.signatures_stripped:
647
+ tried = " and ".join(DNSSEC_FALLBACKS)
648
+ fallback = (
649
+ f" {tried} couldn't be used instead either (a firewall or VPN may block them)."
650
+ if report.stripped_by
651
+ else ""
652
+ )
653
+ return Diagnosis(
654
+ title="Couldn't check DNSSEC: this network strips the signatures",
655
+ explanation=f"This computer's DNS server ({report.nameserver}) answers without "
656
+ "DNSSEC signatures, which some routers, DNS filters and networks remove, so "
657
+ f"nothing can be checked through it.{fallback} This says nothing about "
658
+ f"{name}'s DNSSEC.",
659
+ suggestion="Run this on another network, or with a DNS server that passes the "
660
+ f"signatures along: `dnskit dnssec {name} --server <server>`.",
661
+ )
662
+ reason = report.error or (report.problem.summary if report.problem else "unknown")
663
+ return Diagnosis(
664
+ title="Couldn't check DNSSEC",
665
+ explanation=f"{reason[:1].upper()}{reason[1:]}.",
666
+ suggestion="Try again, or use a resolver that passes DNSSEC records along, such as "
667
+ f"`dnskit dnssec {name} --server 8.8.8.8`.",
668
+ )
669
+
670
+
671
+ def _insecure(report: DnssecReport) -> Diagnosis:
672
+ unsigned = next(z for z in report.zones if z.status is ZoneStatus.UNSIGNED)
673
+ zone = unsigned.zone.rstrip(".")
674
+ parent = dns.name.from_text(unsigned.zone).parent().to_text().rstrip(".") or "the root"
675
+ if unsigned.keys:
676
+ return Diagnosis(
677
+ title=f"DNSSEC is only half set up for {zone}",
678
+ explanation=f"{zone} publishes DNSSEC keys, but {parent} has no DS record for it, "
679
+ "so no chain of trust reaches those keys and resolvers treat the domain as "
680
+ f"unsigned. {PROTECTS}",
681
+ suggestion="Add the DS record your DNS host shows for the zone at your registrar "
682
+ "to finish turning DNSSEC on.",
683
+ )
684
+ return Diagnosis(
685
+ title=f"DNSSEC isn't enabled for {zone}",
686
+ explanation=f"There's no DS record for {zone} at {parent}, so there's no chain of "
687
+ "trust to it. Lookups work normally, but resolvers can't tell a genuine answer from a "
688
+ f"forged one. {PROTECTS}",
689
+ suggestion="To turn it on, enable DNSSEC at your DNS host, then add the DS record it "
690
+ "gives you at your registrar (many hosts do both in one step).",
691
+ )
692
+
693
+
694
+ def _bogus(report: DnssecReport) -> Diagnosis:
695
+ problem = report.problem
696
+ assert problem is not None
697
+ where = problem.zone if isinstance(problem, ZoneCheck) else f"{problem.name} {problem.rtype}"
698
+ where = where.rstrip(".") or "the root"
699
+ consequence = (
700
+ f"Resolvers that validate DNSSEC (Google, Cloudflare, Quad9 and many ISPs) refuse to "
701
+ f"answer for {report.name} (SERVFAIL), so it looks down to most people, while "
702
+ "resolvers that don't validate still answer."
703
+ )
704
+ if problem.kind is BogusKind.EXPIRED and report.clock.state is ClockState.WRONG:
705
+ return Diagnosis(
706
+ title="Validation failed: this computer's clock is wrong",
707
+ explanation=f"{where}: {problem.summary}. {_clock_sentence(report.clock)} "
708
+ "Signatures are only valid between set dates, so with a wrong clock valid "
709
+ "signatures look expired or not yet valid.",
710
+ suggestion="Set the date and time automatically (Windows: Settings > Time & "
711
+ "language > Date & time), then run the check again.",
712
+ )
713
+ match problem.kind:
714
+ case BogusKind.NO_DNSKEY:
715
+ fix = (
716
+ "The registrar still has a DS record, but the zone has no keys: it was "
717
+ "probably moved to a DNS host without DNSSEC. Remove the DS record at the "
718
+ "registrar, or turn DNSSEC on at the new host."
719
+ )
720
+ case BogusKind.DS_MISMATCH:
721
+ fix = (
722
+ "The DS record at the registrar doesn't match the zone's current key, which "
723
+ "happens after a key change or a move to a new DNS host. Replace it with the "
724
+ "DS record your DNS host shows, or remove it to switch DNSSEC off until then."
725
+ )
726
+ case BogusKind.EXPIRED:
727
+ fix = (
728
+ "The zone's signatures have expired, so the DNS host has stopped re-signing "
729
+ "it. Contact the DNS host; if DNSSEC can't be fixed quickly, remove the DS "
730
+ "record at the registrar."
731
+ )
732
+ case _:
733
+ fix = (
734
+ "The zone's signatures don't match its records. Contact the DNS host; if it "
735
+ "can't be fixed quickly, remove the DS record at the registrar."
736
+ )
737
+ return Diagnosis(
738
+ title=f"DNSSEC is broken for {report.name}",
739
+ explanation=f"{where}: {problem.summary}. {consequence}",
740
+ suggestion=fix,
741
+ )
742
+
743
+
744
+ def clock_diagnosis(clock: ClockCheck) -> Diagnosis | None:
745
+ """A warning when this computer's clock looks wrong; None otherwise."""
746
+ if clock.state is not ClockState.WRONG:
747
+ return None
748
+ return Diagnosis(
749
+ title="This computer's clock looks wrong",
750
+ explanation=f"{_clock_sentence(clock)} DNSSEC signatures are only valid between set "
751
+ "dates, so a wrong clock makes valid signatures look expired or not yet valid and "
752
+ "validation fails. It breaks HTTPS certificates too.",
753
+ suggestion="Set the date and time automatically (Windows: Settings > Time & language "
754
+ "> Date & time; macOS: System Settings > General > Date & Time).",
755
+ )
756
+
757
+
758
+ def _clock_sentence(clock: ClockCheck) -> str:
759
+ if clock.reference is None:
760
+ return (
761
+ f"This computer's date, {clock.local:%Y-%m-%d}, is outside the dates the root "
762
+ "zone's signatures are valid for."
763
+ )
764
+ return (
765
+ f"This computer's date is {clock.local:%Y-%m-%d}, but the root zone was published "
766
+ f"on {clock.reference:%Y-%m-%d}."
767
+ )