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/local.py ADDED
@@ -0,0 +1,725 @@
1
+ """Inspect this computer's DNS setup: adapters, their nameservers, ghosts and the hosts file.
2
+
3
+ Problems are returned with plain-English explanations and fixes, so every front end can
4
+ present them its own way.
5
+ """
6
+
7
+ import dataclasses
8
+ import ipaddress
9
+ import os
10
+ import shutil
11
+ import socket
12
+ import sys
13
+ import time
14
+ from collections.abc import Callable
15
+ from concurrent.futures import ThreadPoolExecutor
16
+ from dataclasses import dataclass
17
+ from enum import StrEnum
18
+ from pathlib import Path
19
+
20
+ from dnskit.core.adapters import (
21
+ Adapter,
22
+ AdapterScan,
23
+ RegistryEntry,
24
+ normalize_ip,
25
+ scan_adapters,
26
+ )
27
+ from dnskit.core.connectivity import IPv6Check, IPv6State, check_ipv6
28
+ from dnskit.core.integrity import (
29
+ CLOUDFLARE_WHOAMI,
30
+ GOOGLE_WHOAMI,
31
+ HijackCheck,
32
+ InterceptionCheck,
33
+ Verdict,
34
+ check_cloudflare,
35
+ check_google,
36
+ check_nxdomain,
37
+ )
38
+ from dnskit.core.nameservers import (
39
+ PROBE_TIMEOUT_S,
40
+ SLOW_THRESHOLD_MS,
41
+ SystemNameservers,
42
+ classify_nameservers,
43
+ configured_nameservers,
44
+ probe_all,
45
+ )
46
+
47
+ _INTERFACES_KEY = r"HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces"
48
+
49
+ # Hosts file names that every OS ships with; entries for these don't override real DNS.
50
+ _STANDARD_HOST_NAMES = frozenset(
51
+ {
52
+ "localhost",
53
+ "localhost.localdomain",
54
+ "localhost4",
55
+ "localhost4.localdomain4",
56
+ "localhost6",
57
+ "localhost6.localdomain6",
58
+ "broadcasthost",
59
+ "ip6-localhost",
60
+ "ip6-loopback",
61
+ "ip6-localnet",
62
+ "ip6-mcastprefix",
63
+ "ip6-allnodes",
64
+ "ip6-allrouters",
65
+ "ip6-allhosts",
66
+ }
67
+ )
68
+
69
+ # Public resolvers that are practically never down: when one doesn't answer, something
70
+ # between this computer and it (a firewall, a VPN, the network) is blocking it.
71
+ WELL_KNOWN_RESOLVERS: dict[str, str] = {
72
+ "1.1.1.1": "Cloudflare",
73
+ "1.0.0.1": "Cloudflare",
74
+ "2606:4700:4700::1111": "Cloudflare",
75
+ "2606:4700:4700::1001": "Cloudflare",
76
+ "8.8.8.8": "Google",
77
+ "8.8.4.4": "Google",
78
+ "2001:4860:4860::8888": "Google",
79
+ "2001:4860:4860::8844": "Google",
80
+ "9.9.9.9": "Quad9",
81
+ "149.112.112.112": "Quad9",
82
+ "2620:fe::fe": "Quad9",
83
+ "2620:fe::9": "Quad9",
84
+ "208.67.222.222": "OpenDNS",
85
+ "208.67.220.220": "OpenDNS",
86
+ }
87
+
88
+
89
+ class Severity(StrEnum):
90
+ ERROR = "error" # DNS doesn't work
91
+ WARNING = "warning" # DNS works, but something is misconfigured or slow
92
+
93
+
94
+ class ProblemKind(StrEnum):
95
+ """What a problem is about, so other reports (`doctor`) can weigh it."""
96
+
97
+ NO_ADAPTER = "no_adapter"
98
+ NO_DNS_SERVERS = "no_dns_servers"
99
+ NO_RESPONSE = "no_response" # every DNS server in use is silent
100
+ ADAPTERS_UNREADABLE = "adapters_unreadable"
101
+ SERVER_FAILED = "server_failed"
102
+ VPN_BLOCKED = "vpn_blocked"
103
+ SLOW = "slow"
104
+ GHOST = "ghost"
105
+ HOSTS = "hosts"
106
+ HOSTS_UNREADABLE = "hosts_unreadable"
107
+ HIJACK = "hijack"
108
+ INTERCEPTION = "interception"
109
+ IPV6_BROKEN = "ipv6_broken"
110
+
111
+
112
+ @dataclass(frozen=True)
113
+ class Problem:
114
+ severity: Severity
115
+ title: str
116
+ detail: str
117
+ fix: str
118
+ kind: ProblemKind
119
+
120
+
121
+ @dataclass(frozen=True)
122
+ class ServerCheck:
123
+ nameserver: str
124
+ adapters: tuple[Adapter, ...] # adapters that list it, connected first
125
+ used: bool # lookups use it: it's on a connected adapter (or adapters are unknown)
126
+ ghost: bool # in the OS configuration, but on no connected adapter
127
+ latency_ms: float | None # None: no response within the probe timeout
128
+ registry: tuple[RegistryEntry, ...] = () # Windows: registry values that list it
129
+ public: str | None = None # provider, for a well-known public resolver like 1.1.1.1
130
+ probed: bool = True # False: not tested (a ghost, with probe_ghosts=False)
131
+ # In use and not answering while a VPN is connected, and not on the VPN: most likely
132
+ # the VPN blocks DNS outside its tunnel, rather than the server being down.
133
+ vpn_blocked: bool = False
134
+
135
+ @property
136
+ def failed(self) -> bool:
137
+ return self.probed and self.latency_ms is None
138
+
139
+ @property
140
+ def slow(self) -> bool:
141
+ return self.latency_ms is not None and self.latency_ms > SLOW_THRESHOLD_MS
142
+
143
+ @property
144
+ def adapter_names(self) -> str:
145
+ return ", ".join(a.name for a in self.adapters)
146
+
147
+
148
+ class HostsKind(StrEnum):
149
+ BLOCKED = "blocked" # points at 0.0.0.0 or ::, so the name can't be reached
150
+ LOCAL = "this computer" # points at a loopback address
151
+ REDIRECT = "redirect" # points at some other address
152
+
153
+
154
+ @dataclass(frozen=True)
155
+ class HostsEntry:
156
+ line: int
157
+ ip: str
158
+ names: tuple[str, ...] # non-standard names on the line
159
+ kind: HostsKind
160
+
161
+
162
+ @dataclass(frozen=True)
163
+ class HostsFile:
164
+ path: str
165
+ entries: tuple[HostsEntry, ...] # only lines that could override DNS
166
+ error: str | None = None # why the file couldn't be read (a missing file is no error)
167
+
168
+
169
+ @dataclass(frozen=True)
170
+ class FlushCommand:
171
+ command: str | None # None when there is no system DNS cache to flush
172
+ note: str
173
+
174
+
175
+ @dataclass(frozen=True)
176
+ class LocalReport:
177
+ platform: str # "Windows", "macOS" or "Linux"
178
+ scan: AdapterScan
179
+ nameservers: SystemNameservers
180
+ servers: tuple[ServerCheck, ...] # connected adapters' servers first, then the rest
181
+ hosts: HostsFile
182
+ flush: FlushCommand
183
+ problems: tuple[Problem, ...] # errors first
184
+ probe_timeout: float
185
+ elapsed_ms: float
186
+ hijack: tuple[HijackCheck, ...] = () # one per responding DNS server in use
187
+ interception: tuple[InterceptionCheck, ...] = () # Google, then Cloudflare
188
+ ipv6: IPv6Check | None = None
189
+
190
+ @property
191
+ def has_errors(self) -> bool:
192
+ return any(p.severity is Severity.ERROR for p in self.problems)
193
+
194
+ @property
195
+ def vpns(self) -> tuple[Adapter, ...]:
196
+ """Connected VPN adapters."""
197
+ return self.scan.connected_vpns
198
+
199
+
200
+ def local_check(timeout: float = PROBE_TIMEOUT_S, probe_ghosts: bool = True) -> LocalReport:
201
+ """Inspect the local DNS setup and test every nameserver it mentions, in parallel.
202
+
203
+ First every server is probed while the interception checks run; then the servers in use
204
+ that answered are checked for NXDOMAIN hijacking, and IPv6 is tested through the fastest.
205
+ Without `probe_ghosts`, ghost servers (which nothing uses) aren't tested, which saves
206
+ waiting for the dead ones to time out.
207
+ """
208
+ start = time.perf_counter()
209
+ scan = scan_adapters()
210
+ nameservers = classify_nameservers(configured_nameservers(), scan)
211
+
212
+ candidates = list(dict.fromkeys(_candidates(scan, nameservers)))
213
+ with ThreadPoolExecutor(max_workers=8) as pool:
214
+ to_probe = [ns for ns in candidates if probe_ghosts or ns not in nameservers.ignored]
215
+ probes = pool.submit(probe_all, to_probe, timeout)
216
+ google = pool.submit(check_google, timeout)
217
+ cloudflare = pool.submit(check_cloudflare, timeout)
218
+ latencies = {p.nameserver: p.latency_ms for p in probes.result()}
219
+ servers = tuple(
220
+ _vpn_aware(
221
+ ServerCheck(
222
+ nameserver=ns,
223
+ adapters=scan.adapters_listing(ns),
224
+ used=ns in nameservers.usable or _on_connected_adapter(scan, ns),
225
+ ghost=ns in nameservers.ignored,
226
+ latency_ms=latencies.get(ns),
227
+ registry=scan.registry_listing(ns),
228
+ public=public_resolver(ns),
229
+ probed=ns in to_probe,
230
+ ),
231
+ vpn_connected=bool(scan.connected_vpns),
232
+ )
233
+ for ns in candidates
234
+ )
235
+
236
+ # Servers in use that answered, fastest first.
237
+ answering = [
238
+ s.nameserver
239
+ for s in sorted(servers, key=lambda s: s.latency_ms or 0.0)
240
+ if s.used and not s.failed
241
+ ]
242
+ hijacks = [pool.submit(check_nxdomain, ns, timeout) for ns in answering]
243
+ ipv6 = pool.submit(check_ipv6, answering, timeout)
244
+ hijack = tuple(f.result() for f in hijacks)
245
+ interception = (google.result(), cloudflare.result())
246
+ ipv6_check = ipv6.result()
247
+
248
+ hosts = read_hosts()
249
+ platform = platform_name()
250
+ problems = _problems(scan, servers, hosts, platform, timeout)
251
+ problems += _check_problems(hijack, interception, ipv6_check, scan.connected_vpns)
252
+ problems = tuple(sorted(problems, key=lambda p: p.severity is not Severity.ERROR))
253
+ return LocalReport(
254
+ platform=platform,
255
+ scan=scan,
256
+ nameservers=nameservers,
257
+ servers=servers,
258
+ hosts=hosts,
259
+ flush=flush_command(),
260
+ problems=problems,
261
+ probe_timeout=timeout,
262
+ elapsed_ms=(time.perf_counter() - start) * 1000,
263
+ hijack=hijack,
264
+ interception=interception,
265
+ ipv6=ipv6_check,
266
+ )
267
+
268
+
269
+ def platform_name(platform: str | None = None) -> str:
270
+ platform = sys.platform if platform is None else platform
271
+ if platform == "win32":
272
+ return "Windows"
273
+ if platform == "darwin":
274
+ return "macOS"
275
+ return "Linux"
276
+
277
+
278
+ def _candidates(scan: AdapterScan, nameservers: SystemNameservers) -> list[str]:
279
+ """Connected adapters' servers in adapter order, then the configured ones not yet seen."""
280
+ return [ns for a in scan.connected for ns in a.dns_servers] + list(nameservers.configured)
281
+
282
+
283
+ def _on_connected_adapter(scan: AdapterScan, nameserver: str) -> bool:
284
+ return any(a.connected for a in scan.adapters_listing(nameserver))
285
+
286
+
287
+ def public_resolver(nameserver: str) -> str | None:
288
+ """The provider of a well-known public resolver (e.g. "Cloudflare"), else None."""
289
+ return WELL_KNOWN_RESOLVERS.get(normalize_ip(nameserver))
290
+
291
+
292
+ def _vpn_aware(server: ServerCheck, vpn_connected: bool) -> ServerCheck:
293
+ """Mark a failing server outside a connected VPN as probably blocked by that VPN."""
294
+ blocked = (
295
+ vpn_connected
296
+ and server.used
297
+ and server.failed
298
+ and bool(server.adapters)
299
+ and not any(a.vpn for a in server.adapters)
300
+ )
301
+ return dataclasses.replace(server, vpn_blocked=blocked) if blocked else server
302
+
303
+
304
+ # --- Hosts file ---------------------------------------------------------------------------
305
+
306
+
307
+ def hosts_path(platform: str | None = None) -> Path:
308
+ """Where the OS keeps its hosts file."""
309
+ if platform_name(platform) == "Windows":
310
+ root = os.environ.get("SYSTEMROOT", r"C:\Windows")
311
+ return Path(root) / "System32" / "drivers" / "etc" / "hosts"
312
+ return Path("/etc/hosts")
313
+
314
+
315
+ def read_hosts(path: Path | None = None) -> HostsFile:
316
+ """The hosts file's entries that could override DNS. Never raises."""
317
+ path = hosts_path() if path is None else path
318
+ try:
319
+ text = path.read_bytes().decode("utf-8", errors="replace")
320
+ except FileNotFoundError:
321
+ return HostsFile(str(path), ())
322
+ except OSError as exc:
323
+ return HostsFile(str(path), (), error=exc.strerror or str(exc))
324
+ return HostsFile(str(path), tuple(parse_hosts(text, socket.gethostname())))
325
+
326
+
327
+ def parse_hosts(text: str, hostname: str = "") -> list[HostsEntry]:
328
+ """Entries naming anything beyond the OS defaults (localhost, this computer's name)."""
329
+ standard = set(_STANDARD_HOST_NAMES)
330
+ if hostname:
331
+ standard |= {hostname.lower(), hostname.split(".", 1)[0].lower()}
332
+
333
+ entries = []
334
+ for number, line in enumerate(text.lstrip("\ufeff").splitlines(), start=1):
335
+ fields = line.split("#", 1)[0].split()
336
+ if len(fields) < 2:
337
+ continue
338
+ ip, names = fields[0], tuple(n for n in fields[1:] if n.lower() not in standard)
339
+ try:
340
+ address = ipaddress.ip_address(ip.split("%", 1)[0])
341
+ except ValueError:
342
+ continue # not a valid line; the OS ignores it too
343
+ if not names:
344
+ continue
345
+ if address.is_unspecified:
346
+ kind = HostsKind.BLOCKED
347
+ elif address.is_loopback:
348
+ kind = HostsKind.LOCAL
349
+ else:
350
+ kind = HostsKind.REDIRECT
351
+ entries.append(HostsEntry(number, ip, names, kind))
352
+ return entries
353
+
354
+
355
+ # --- Flushing the DNS cache ---------------------------------------------------------------
356
+
357
+
358
+ def flush_command(
359
+ platform: str | None = None, which: Callable[[str], str | None] = shutil.which
360
+ ) -> FlushCommand:
361
+ """The command that clears the OS's DNS cache."""
362
+ match platform_name(platform):
363
+ case "Windows":
364
+ return FlushCommand(
365
+ "ipconfig /flushdns",
366
+ "Browsers keep their own DNS cache too; restart the browser if a site still "
367
+ "goes to the old address.",
368
+ )
369
+ case "macOS":
370
+ return FlushCommand(
371
+ "sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder",
372
+ "It asks for your password. Restart the browser too; it keeps its own cache.",
373
+ )
374
+ if which("resolvectl"):
375
+ return FlushCommand("sudo resolvectl flush-caches", "Clears systemd-resolved's cache.")
376
+ if which("nscd"):
377
+ return FlushCommand("sudo nscd --invalidate=hosts", "Clears nscd's hosts cache.")
378
+ return FlushCommand(
379
+ None,
380
+ "No DNS cache service (systemd-resolved or nscd) was found, so the system doesn't "
381
+ "cache DNS answers. Restart the browser or app to clear its own cache.",
382
+ )
383
+
384
+
385
+ # --- Problems -----------------------------------------------------------------------------
386
+
387
+
388
+ def _problems(
389
+ scan: AdapterScan,
390
+ servers: tuple[ServerCheck, ...],
391
+ hosts: HostsFile,
392
+ platform: str,
393
+ timeout: float,
394
+ ) -> tuple[Problem, ...]:
395
+ problems: list[Problem] = []
396
+ used = [s for s in servers if s.used]
397
+
398
+ if scan.error:
399
+ problems.append(
400
+ Problem(
401
+ Severity.WARNING,
402
+ "Couldn't read the network adapters",
403
+ f"{scan.error}. Without them, nameservers can't be matched to adapters, so "
404
+ "every configured nameserver is treated as in use.",
405
+ "Run dnskit local again; if it keeps happening, please report it.",
406
+ ProblemKind.ADAPTERS_UNREADABLE,
407
+ )
408
+ )
409
+ elif not scan.connected:
410
+ problems.append(
411
+ Problem(
412
+ Severity.ERROR,
413
+ "No network adapter is connected",
414
+ "Every network adapter is disconnected, so this computer can't reach any DNS "
415
+ "server.",
416
+ "Connect to Wi-Fi or plug in a network cable, then run dnskit local again.",
417
+ ProblemKind.NO_ADAPTER,
418
+ )
419
+ )
420
+ elif scan.dns_per_adapter and not any(a.dns_servers for a in scan.connected):
421
+ problems.append(
422
+ Problem(
423
+ Severity.ERROR,
424
+ "No DNS servers on the connected adapters",
425
+ f"{_names(scan.connected)} {_is_are(scan.connected)} connected, but no DNS "
426
+ "server is set, so names can't be looked up.",
427
+ "Set the adapter to get DNS servers automatically (DHCP), or enter servers "
428
+ "by hand, such as 1.1.1.1 and 8.8.8.8, in its network settings.",
429
+ ProblemKind.NO_DNS_SERVERS,
430
+ )
431
+ )
432
+
433
+ vpns = scan.connected_vpns
434
+ if used and all(s.failed for s in used):
435
+ listed = ", ".join(_server_label(s) for s in used)
436
+ detail = f"None of the DNS servers in use answered within {timeout:g} s: {listed}."
437
+ fix = (
438
+ "Check that you're online (try a web page by IP address), restart the router, "
439
+ "or temporarily set the adapter's DNS servers to 1.1.1.1 and 8.8.8.8."
440
+ )
441
+ if vpns:
442
+ detail += f" {_names(vpns)} (VPN) {_is_are(vpns)} connected."
443
+ fix = (
444
+ f"Reconnect {_names(vpns)}, or disconnect it and run dnskit local again to "
445
+ "test the other servers without it. If they still fail: " + fix[0].lower()
446
+ ) + fix[1:]
447
+ problems.append(
448
+ Problem(
449
+ Severity.ERROR,
450
+ "No DNS server is responding",
451
+ detail + _public_note(used),
452
+ fix,
453
+ ProblemKind.NO_RESPONSE,
454
+ )
455
+ )
456
+ else:
457
+ blocked = tuple(s for s in used if s.vpn_blocked)
458
+ if blocked:
459
+ problems.append(_vpn_blocked_problem(blocked, vpns, timeout))
460
+ for server in used:
461
+ if server.failed and not server.vpn_blocked:
462
+ problems.append(_failed_problem(server, timeout))
463
+ elif server.slow:
464
+ problems.append(_slow_problem(server))
465
+
466
+ problems.extend(_ghost_problem(s, platform) for s in servers if s.ghost)
467
+
468
+ if hosts.error:
469
+ problems.append(
470
+ Problem(
471
+ Severity.WARNING,
472
+ "Couldn't read the hosts file",
473
+ f"{hosts.path}: {hosts.error}.",
474
+ "Open it as an administrator to check for entries that override DNS.",
475
+ ProblemKind.HOSTS_UNREADABLE,
476
+ )
477
+ )
478
+ elif hosts.entries:
479
+ problems.append(_hosts_problem(hosts))
480
+
481
+ return tuple(sorted(problems, key=lambda p: p.severity is not Severity.ERROR))
482
+
483
+
484
+ def _failed_problem(server: ServerCheck, timeout: float) -> Problem:
485
+ where = f"{server.adapter_names}'s" if server.adapters else "the adapter's"
486
+ detail = (
487
+ f"It didn't answer a test query within {timeout:g} s. Lookups that try it first wait "
488
+ "for it to time out before moving on to the next server."
489
+ )
490
+ if server.public:
491
+ fix = (
492
+ "Check whether a firewall, antivirus or VPN on this computer blocks DNS, or "
493
+ "whether this network only allows its own DNS server (common at work, schools "
494
+ f"and hotels). If it does, remove {server.nameserver} from {where} DNS settings "
495
+ "and use the network's DNS server instead."
496
+ )
497
+ elif any(a.vpn for a in server.adapters):
498
+ fix = (
499
+ f"It's set by the VPN ({server.adapter_names}). Reconnect the VPN; if it keeps "
500
+ "failing, ask whoever runs the VPN to check its DNS server."
501
+ )
502
+ else:
503
+ fix = (
504
+ f"If it keeps failing, remove it from {where} DNS settings, or check the device "
505
+ f"at {server.nameserver} (often the router)."
506
+ )
507
+ return Problem(
508
+ Severity.WARNING,
509
+ f"DNS server {_server_label(server)} isn't responding",
510
+ detail + _public_note((server,)),
511
+ fix,
512
+ ProblemKind.SERVER_FAILED,
513
+ )
514
+
515
+
516
+ def _vpn_blocked_problem(
517
+ servers: tuple[ServerCheck, ...], vpns: tuple[Adapter, ...], timeout: float
518
+ ) -> Problem:
519
+ one = len(servers) == 1
520
+ vpn = _names(vpns)
521
+ listed = ", ".join(_server_label(s) for s in servers)
522
+ return Problem(
523
+ Severity.WARNING,
524
+ f"{'A DNS server' if one else 'DNS servers'} outside the VPN "
525
+ f"{'isn' if one else 'aren'}'t responding",
526
+ f"{listed} didn't answer within {timeout:g} s while {vpn} (VPN) {_is_are(vpns)} "
527
+ "connected. Many VPNs send all traffic through the tunnel, or block DNS queries that "
528
+ "go around it (DNS leak protection), so DNS servers on other adapters can't be "
529
+ f"reached while the VPN is on. {'It is' if one else 'They are'} probably fine.",
530
+ f"Don't remove {'it' if one else 'them'}. To test {'it' if one else 'them'}, "
531
+ f"disconnect {vpn} and run dnskit local again. Meanwhile, lookups use the DNS "
532
+ "servers that do answer.",
533
+ ProblemKind.VPN_BLOCKED,
534
+ )
535
+
536
+
537
+ def _public_note(servers: tuple[ServerCheck, ...] | list[ServerCheck]) -> str:
538
+ """A sentence noting that silent well-known public resolvers are blocked, not down."""
539
+ public = [s for s in servers if s.public and s.failed]
540
+ if not public:
541
+ return ""
542
+ names = ", ".join(f"{s.nameserver} ({s.public})" for s in public)
543
+ if len(public) == 1:
544
+ return (
545
+ f" {names} is a well-known public DNS service that's almost never down, so no "
546
+ "response usually means a firewall or VPN is blocking it."
547
+ )
548
+ return (
549
+ f" {names} are well-known public DNS services that are almost never down, so no "
550
+ "response usually means a firewall or VPN is blocking them."
551
+ )
552
+
553
+
554
+ def _slow_problem(server: ServerCheck) -> Problem:
555
+ return Problem(
556
+ Severity.WARNING,
557
+ f"DNS server {_server_label(server)} is slow",
558
+ f"It answered in {server.latency_ms:.0f} ms; a healthy DNS server usually answers in "
559
+ f"under {SLOW_THRESHOLD_MS:.0f} ms.",
560
+ "Run dnskit local again to see whether it's consistently slow. If it is, consider a "
561
+ "faster DNS server such as 1.1.1.1 or 8.8.8.8 in the adapter's settings.",
562
+ ProblemKind.SLOW,
563
+ )
564
+
565
+
566
+ def _ghost_problem(server: ServerCheck, platform: str) -> Problem:
567
+ ns = server.nameserver
568
+ if not server.probed:
569
+ responds = "It wasn't tested, since it isn't used."
570
+ elif server.failed:
571
+ responds = "It doesn't respond, so they wait for it to time out." + _public_note((server,))
572
+ else:
573
+ responds = f"It does respond ({server.latency_ms:.0f} ms)."
574
+ readers = "programs that read the system configuration directly (such as dnspython)"
575
+ if server.adapters:
576
+ adapters = server.adapters
577
+ detail = (
578
+ f"It's set on {_names(adapters)}, which {_is_are(adapters)} disconnected. "
579
+ f"{platform} ignores it until that adapter reconnects, but {readers} still try "
580
+ "it. " + responds
581
+ )
582
+ fix = (
583
+ "Nothing to do. dnskit ignores it too. If it doesn't answer once "
584
+ f"{_names(adapters)} reconnects, change that adapter's DNS settings."
585
+ )
586
+ else:
587
+ detail = (
588
+ f"It's in the system configuration but on no network adapter, probably left "
589
+ f"behind by a removed adapter, a VPN or an old DHCP lease. {readers.capitalize()} "
590
+ "still try it. " + responds
591
+ )
592
+ if platform == "Windows" and server.registry:
593
+ values = ", ".join(f"{e.interface_id} ({e.value})" for e in server.registry)
594
+ fix = (
595
+ f"dnskit ignores it. To remove it, delete {ns} from these values under "
596
+ f"{_INTERFACES_KEY} in the registry (needs administrator rights): {values}."
597
+ )
598
+ elif platform == "Windows":
599
+ fix = "dnskit ignores it, and so does Windows; no change is needed."
600
+ else:
601
+ fix = f"dnskit ignores it. To remove it, delete {ns} from /etc/resolv.conf or "
602
+ fix += "your network settings."
603
+ title = f"Ghost DNS server {ns}"
604
+ if server.adapters:
605
+ title += f" (on disconnected {_names(server.adapters)})"
606
+ return Problem(Severity.WARNING, title, detail, fix, ProblemKind.GHOST)
607
+
608
+
609
+ def _hosts_problem(hosts: HostsFile) -> Problem:
610
+ pairs = [f"{name} → {e.ip}" for e in hosts.entries for name in e.names]
611
+ shown = ", ".join(pairs[:5])
612
+ more = f" and {len(pairs) - 5} more" if len(pairs) > 5 else ""
613
+ count = f"{len(pairs)} name" + ("" if len(pairs) == 1 else "s")
614
+ return Problem(
615
+ Severity.WARNING,
616
+ f"The hosts file overrides DNS for {count}",
617
+ f"{shown}{more}. Browsers and most apps use these addresses without asking DNS, so "
618
+ "dnskit lookups (which ask DNS directly) won't show them.",
619
+ f"If one of these names goes to the wrong place, remove or comment out its line in "
620
+ f"{hosts.path} (needs administrator rights), then flush the DNS cache.",
621
+ ProblemKind.HOSTS,
622
+ )
623
+
624
+
625
+ def _check_problems(
626
+ hijack: tuple[HijackCheck, ...],
627
+ interception: tuple[InterceptionCheck, ...],
628
+ ipv6: IPv6Check,
629
+ vpns: tuple[Adapter, ...],
630
+ ) -> tuple[Problem, ...]:
631
+ """Problems from the hijacking, interception and IPv6 checks (all warnings)."""
632
+ problems = [_hijack_problem(h) for h in hijack if h.verdict is Verdict.SUSPECT]
633
+ problems += [
634
+ _interception_problem(c, vpns) for c in interception if c.verdict is Verdict.SUSPECT
635
+ ]
636
+ if ipv6.state is IPv6State.BROKEN:
637
+ problems.append(_ipv6_problem(ipv6))
638
+ return tuple(problems)
639
+
640
+
641
+ def _hijack_problem(check: HijackCheck) -> Problem:
642
+ return Problem(
643
+ Severity.WARNING,
644
+ f"DNS server {check.nameserver} answers for names that don't exist (NXDOMAIN hijacking)",
645
+ f"Asked for {check.probe_name}, a made-up name, it answered {', '.join(check.addresses)} "
646
+ "instead of saying the name doesn't exist. ISPs and some routers do this to send "
647
+ "mistyped addresses to a search or advertising page. It also breaks programs that rely "
648
+ 'on "doesn\'t exist" (a typo in a server name looks like it works), and can confuse '
649
+ "VPNs and company networks.",
650
+ 'Turn off "DNS assist", "error redirect" or "search assist" in your router or ISP '
651
+ "account, or use a resolver that doesn't do this, such as 1.1.1.1, 8.8.8.8 or 9.9.9.9.",
652
+ ProblemKind.HIJACK,
653
+ )
654
+
655
+
656
+ def _interception_problem(check: InterceptionCheck, vpns: tuple[Adapter, ...]) -> Problem:
657
+ if check.provider == "Google" and check.answered_by:
658
+ how = (
659
+ f"Google answers this test ({GOOGLE_WHOAMI}) with the address of its own DNS "
660
+ f"server that asked, but the answer named {check.answered_by}, which isn't "
661
+ f"Google's. So a query sent to {check.nameserver} was answered by another DNS server."
662
+ )
663
+ elif check.provider == "Google":
664
+ how = (
665
+ f"Google always answers this test ({GOOGLE_WHOAMI}) with an address, but got "
666
+ f"{check.response}. Another DNS server most likely answered in Google's place."
667
+ )
668
+ else:
669
+ how = (
670
+ f"Cloudflare always answers this test ({CLOUDFLARE_WHOAMI}, class CH) with your "
671
+ f"address, but got {check.response}. Another DNS server most likely answered in "
672
+ "Cloudflare's place."
673
+ )
674
+ why = (
675
+ f" {_names(vpns)} (VPN) {_is_are(vpns)} connected: VPNs often redirect all DNS to "
676
+ "their own servers on purpose, to stop DNS leaks."
677
+ if vpns
678
+ else " Routers, firewalls, ISPs and work, school or hotel networks do this to filter "
679
+ "or log DNS."
680
+ )
681
+ fix = (
682
+ f"If it's the VPN, that's expected: disconnect {_names(vpns)} and run dnskit local again "
683
+ "to check the network itself."
684
+ if vpns
685
+ else "On a work, school or hotel network this is usually deliberate filtering. At home, "
686
+ 'look for "DNS redirect", "DNS proxy" or parental-control options in the router, or '
687
+ "ask your ISP. Encrypted DNS (DNS over HTTPS in the browser or OS) gets around it."
688
+ )
689
+ return Problem(
690
+ Severity.WARNING,
691
+ f"Queries to {check.nameserver} ({check.provider}) appear to be intercepted",
692
+ how + why + " Answers can be filtered or changed without you knowing.",
693
+ fix,
694
+ ProblemKind.INTERCEPTION,
695
+ )
696
+
697
+
698
+ def _ipv6_problem(check: IPv6Check) -> Problem:
699
+ attempt = check.attempt
700
+ failure = f"{attempt.error} ({attempt.message})" if attempt and attempt.message else "failed"
701
+ target = attempt.address if attempt else check.host
702
+ return Problem(
703
+ Severity.WARNING,
704
+ "IPv6 is broken: names resolve to IPv6 addresses, but connecting to them fails",
705
+ f"This computer has an IPv6 address ({check.local_address}) and AAAA lookups work, but "
706
+ f"connecting to {check.host} at {target} {failure}. Browsers and apps try IPv6 first "
707
+ "and only fall back to IPv4 after it fails, so sites can load slowly or time out.",
708
+ "Restart the router. If it keeps happening, the router or ISP has a half-working "
709
+ "IPv6 setup: turn IPv6 off in the router (or on this adapter) until the ISP fixes it.",
710
+ ProblemKind.IPV6_BROKEN,
711
+ )
712
+
713
+
714
+ def _server_label(server: ServerCheck) -> str:
715
+ if server.adapters:
716
+ return f"{server.nameserver} ({server.adapter_names})"
717
+ return server.nameserver
718
+
719
+
720
+ def _names(adapters: tuple[Adapter, ...]) -> str:
721
+ return ", ".join(a.name for a in adapters)
722
+
723
+
724
+ def _is_are(items: tuple[Adapter, ...]) -> str:
725
+ return "is" if len(items) == 1 else "are"