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.
@@ -0,0 +1,232 @@
1
+ """Is this computer getting honest DNS answers? NXDOMAIN hijacking and DNS interception.
2
+
3
+ - NXDOMAIN hijacking: a resolver answers a name that can't exist with an address (usually
4
+ a search or advertising page) instead of "doesn't exist".
5
+ - Interception: something on the path (router, network, ISP, VPN) answers queries meant
6
+ for a public resolver such as 8.8.8.8 itself. Google and Cloudflare each have a name that
7
+ only they answer in a recognisable way, which shows who really answered.
8
+ """
9
+
10
+ import ipaddress
11
+ import secrets
12
+ from dataclasses import dataclass
13
+ from enum import StrEnum
14
+
15
+ import dns.exception
16
+ import dns.message
17
+ import dns.query
18
+ import dns.rcode
19
+ import dns.rdata
20
+ import dns.rdatatype
21
+
22
+ GOOGLE_DNS = "8.8.8.8"
23
+ CLOUDFLARE_DNS = "1.1.1.1"
24
+ # Google answers this TXT with the address of its resolver that asked (one of Google's).
25
+ GOOGLE_WHOAMI = "o-o.myaddr.l.google.com"
26
+ # Cloudflare answers this CHAOS-class TXT with your public address; other resolvers can't.
27
+ CLOUDFLARE_WHOAMI = "whoami.cloudflare"
28
+
29
+ # Google's address blocks (AS15169), which its public DNS resolvers ask from. They cover
30
+ # every prefix in https://www.gstatic.com/ipranges/publicdns.json (checked 2026-10-31).
31
+ _GOOGLE_NETWORKS = tuple(
32
+ ipaddress.ip_network(net)
33
+ for net in (
34
+ "8.8.4.0/24",
35
+ "8.8.8.0/24",
36
+ "8.34.208.0/20",
37
+ "8.35.192.0/20",
38
+ "34.64.0.0/10",
39
+ "34.128.0.0/10",
40
+ "35.184.0.0/13",
41
+ "64.233.160.0/19",
42
+ "66.102.0.0/20",
43
+ "66.249.64.0/19",
44
+ "72.14.192.0/18",
45
+ "74.114.28.0/22",
46
+ "74.125.0.0/16",
47
+ "108.170.192.0/18",
48
+ "108.177.0.0/17",
49
+ "142.250.0.0/15",
50
+ "172.217.0.0/16",
51
+ "172.253.0.0/16",
52
+ "173.194.0.0/16",
53
+ "192.178.0.0/15",
54
+ "209.85.128.0/17",
55
+ "216.58.192.0/19",
56
+ "216.239.32.0/19",
57
+ "2001:4860::/32",
58
+ "2404:6800::/32",
59
+ "2404:f340::/32",
60
+ "2600:1900::/28",
61
+ "2607:f8b0::/32",
62
+ "2800:3f0::/32",
63
+ "2a00:1450::/32",
64
+ "2c0f:fb50::/32",
65
+ )
66
+ )
67
+
68
+
69
+ class Verdict(StrEnum):
70
+ OK = "ok"
71
+ SUSPECT = "suspect" # hijacked or intercepted
72
+ UNKNOWN = "unknown" # no usable answer, so it can't be told
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class RawAnswer:
77
+ """One query's outcome, before any interpretation."""
78
+
79
+ rcode: str | None # "NOERROR", "NXDOMAIN", ...; None when nothing came back
80
+ values: tuple[str, ...] = () # the answer's records of the asked type (TXT unquoted)
81
+ error: str | None = None # why nothing came back
82
+
83
+
84
+ @dataclass(frozen=True)
85
+ class HijackCheck:
86
+ nameserver: str
87
+ probe_name: str # the made-up name that was asked for
88
+ verdict: Verdict
89
+ addresses: tuple[str, ...] # what came back instead of "doesn't exist"
90
+ summary: str
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class InterceptionCheck:
95
+ provider: str # "Google" or "Cloudflare"
96
+ nameserver: str # the address the query was sent to
97
+ verdict: Verdict
98
+ answered_by: str | None # the address the answer reveals, when it reveals one
99
+ summary: str
100
+ response: str = "" # what came back, in words (e.g. "SERVFAIL", "no response")
101
+
102
+
103
+ def ask(nameserver: str, name: str, rdtype: str, timeout: float, rdclass: str = "IN") -> RawAnswer:
104
+ """Send one query straight to `nameserver` (no fallback, no retries). Never raises."""
105
+ query = dns.message.make_query(name, rdtype, rdclass)
106
+ try:
107
+ response = dns.query.udp(query, nameserver, timeout=timeout)
108
+ except dns.exception.Timeout:
109
+ return RawAnswer(None, error="no response")
110
+ except (OSError, dns.exception.DNSException) as exc:
111
+ return RawAnswer(None, error=str(exc) or type(exc).__name__)
112
+ wanted = dns.rdatatype.from_text(rdtype)
113
+ values = tuple(
114
+ _rdata_text(rdata) for rrset in response.answer if rrset.rdtype == wanted for rdata in rrset
115
+ )
116
+ return RawAnswer(dns.rcode.to_text(response.rcode()), values)
117
+
118
+
119
+ def _rdata_text(rdata: dns.rdata.Rdata) -> str:
120
+ strings = getattr(rdata, "strings", None) # TXT: join the strings, without quotes
121
+ if strings is not None:
122
+ return b"".join(strings).decode("utf-8", "replace")
123
+ return rdata.to_text()
124
+
125
+
126
+ # --- NXDOMAIN hijacking -------------------------------------------------------------------
127
+
128
+
129
+ def probe_name() -> str:
130
+ """A random name that can't exist, under a real top-level domain."""
131
+ return f"dnskit-nx-{secrets.token_hex(8)}.com"
132
+
133
+
134
+ def check_nxdomain(nameserver: str, timeout: float, name: str | None = None) -> HijackCheck:
135
+ """Ask `nameserver` for a made-up name; an honest resolver says it doesn't exist."""
136
+ name = probe_name() if name is None else name
137
+ return classify_nxdomain(nameserver, name, ask(nameserver, name, "A", timeout))
138
+
139
+
140
+ def classify_nxdomain(nameserver: str, name: str, answer: RawAnswer) -> HijackCheck:
141
+ if answer.rcode == "NXDOMAIN":
142
+ return HijackCheck(nameserver, name, Verdict.OK, (), 'answers "doesn\'t exist" honestly')
143
+ if answer.rcode == "NOERROR" and answer.values:
144
+ shown = ", ".join(answer.values)
145
+ return HijackCheck(
146
+ nameserver,
147
+ name,
148
+ Verdict.SUSPECT,
149
+ answer.values,
150
+ f"hijacked: a made-up name got {shown}",
151
+ )
152
+ reason = answer.error or f"answered {answer.rcode} without an address"
153
+ return HijackCheck(nameserver, name, Verdict.UNKNOWN, (), f"couldn't tell ({reason})")
154
+
155
+
156
+ # --- Interception -------------------------------------------------------------------------
157
+
158
+
159
+ def check_google(timeout: float) -> InterceptionCheck:
160
+ return classify_google(ask(GOOGLE_DNS, GOOGLE_WHOAMI, "TXT", timeout))
161
+
162
+
163
+ def check_cloudflare(timeout: float) -> InterceptionCheck:
164
+ return classify_cloudflare(ask(CLOUDFLARE_DNS, CLOUDFLARE_WHOAMI, "TXT", timeout, "CH"))
165
+
166
+
167
+ def classify_google(answer: RawAnswer) -> InterceptionCheck:
168
+ """Google answers with one of its own resolvers' addresses; anyone else gives theirs."""
169
+ if answer.rcode is None:
170
+ return _unknown("Google", GOOGLE_DNS, answer)
171
+ got = _describe(answer)
172
+ addresses = [ip for ip in map(_parse_ip, answer.values) if ip is not None]
173
+ if not addresses:
174
+ return InterceptionCheck(
175
+ "Google", GOOGLE_DNS, Verdict.SUSPECT, None, f"intercepted: got {got}", got
176
+ )
177
+ google = next((ip for ip in addresses if _is_google(ip)), None)
178
+ if google is not None:
179
+ return InterceptionCheck(
180
+ "Google", GOOGLE_DNS, Verdict.OK, str(google), f"answered by Google ({google})", got
181
+ )
182
+ other = str(addresses[0])
183
+ return InterceptionCheck(
184
+ "Google",
185
+ GOOGLE_DNS,
186
+ Verdict.SUSPECT,
187
+ other,
188
+ f"intercepted: answered from {other}, which isn't Google",
189
+ got,
190
+ )
191
+
192
+
193
+ def classify_cloudflare(answer: RawAnswer) -> InterceptionCheck:
194
+ """Cloudflare answers with your public address; other resolvers refuse or fail."""
195
+ if answer.rcode is None:
196
+ return _unknown("Cloudflare", CLOUDFLARE_DNS, answer)
197
+ got = _describe(answer)
198
+ address = next((ip for ip in map(_parse_ip, answer.values) if ip is not None), None)
199
+ if answer.rcode == "NOERROR" and address is not None:
200
+ return InterceptionCheck(
201
+ "Cloudflare", CLOUDFLARE_DNS, Verdict.OK, str(address), "answered by Cloudflare", got
202
+ )
203
+ return InterceptionCheck(
204
+ "Cloudflare", CLOUDFLARE_DNS, Verdict.SUSPECT, None, f"intercepted: got {got}", got
205
+ )
206
+
207
+
208
+ def _unknown(provider: str, nameserver: str, answer: RawAnswer) -> InterceptionCheck:
209
+ reason = answer.error or "no response"
210
+ return InterceptionCheck(
211
+ provider, nameserver, Verdict.UNKNOWN, None, f"couldn't tell ({reason})", reason
212
+ )
213
+
214
+
215
+ def _describe(answer: RawAnswer) -> str:
216
+ if answer.rcode != "NOERROR":
217
+ return answer.rcode or "nothing"
218
+ if not answer.values:
219
+ return "an empty answer"
220
+ shown = [v for v in answer.values if _parse_ip(v) is not None] or list(answer.values[:1])
221
+ return ", ".join(shown) # addresses only: Google also returns the client's subnet
222
+
223
+
224
+ def _parse_ip(text: str) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None:
225
+ try:
226
+ return ipaddress.ip_address(text.strip())
227
+ except ValueError:
228
+ return None
229
+
230
+
231
+ def _is_google(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
232
+ return any(ip.version == net.version and ip in net for net in _GOOGLE_NETWORKS)