Debian Codegraph @

blaeu-resolve

raw symbols SCIP
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 """ Python code to start a RIPE Atlas UDM (User-Defined
5 Measurement). This one is for running DNS to resolve a name from many
6 places, in order to survey local cache poisonings, effect of
7 hijackings and other DNS rejuvenation effects.
8
9 You'll need an API key in ~/.atlas/auth.
10
11 After launching the measurement, it downloads the results and analyzes
12 them.
13
14 Stéphane Bortzmeyer <[email protected]>
15 """
16
17 import json
18 import sys
19 import time
20 import base64
21 import copy
22 import collections
23
24 # DNS Python http://www.dnspython.org/
25 import dns.message
26
27 import Blaeu
28 from Blaeu import Host_Type
29
30 config = Blaeu.Config()
31 # Default values
32 config.qtype = 'AAAA'
33 config.qclass = "IN"
34 config.display_resolvers = False
35 config.display_rtt = False
36 config.display_validation = False
37 config.edns_size = None
38 config.dnssec = False
39 config.dnssec_checking = True
40 config.nameserver = None
41 config.recursive = True
42 config.sort = False
43 config.nsid = False
44 config.ede = False
45 config.only_one_per_probe = True
46 config.protocol = "UDP"
47 config.tls = False
48 config.probe_id = False
49 config.answer_section = True
50 config.authority_section = False
51 config.additional_section = False
52
53 # Local values
54 edns_size = None
55
56 # Constants
57 MAXLEN = 80 # Maximum length of a displayed resource record
58
59 class Set():
60 def __init__(self):
61 self.total = 0
62 self.successes = 0
63 self.rtt = 0
64
65 def usage(msg=None):
66 print("Usage: %s domain-name" % sys.argv[0], file=sys.stderr)
67 config.usage(msg)
68 print("""Also:
69 --displayresolvers or -l : display the resolvers IP addresses (WARNING: big lists)
70 --norecursive or -Z : asks the resolver to NOT recurse (default is to recurse, note --norecursive works ONLY if asking a specific resolver, not with the default one)
71 --dnssec or -D : asks the resolver the DNSSEC records
72 --nsid : asks the resolver with NSID (name server identification)
73 --ede : displays EDE (Extended DNS Errors)
74 --ednssize=N or -B N : asks for EDNS with the "payload size" option (default is very old DNS, without EDNS)
75 --tcp: uses TCP (default is UDP)
76 --tls: uses TLS (implies TCP)
77 --checkingdisabled or -k : asks the resolver to NOT perform DNSSEC validation
78 --displayvalidation or -j : displays the DNSSEC validation status
79 --displayrtt : displays the average RTT
80 --authority : displays the Authority section of the answer
81 --additional : displays the Additional section of the answer
82 --sort or -S : sort the result sets
83 --type or -q : query type (default is %s)
84 --class : query class (default is %s)
85 --severalperprobe : count all the resolvers of each probe (default is to count only the first to reply)
86 --nameserver=name_or_IPaddr[,...] or -x name_or_IPaddr : query this name server (default is to query the probe's resolver)
87 --probe_id : prepend probe ID (and timestamp) to the domain name (default is to abstain)
88 """ % (config.qtype, config.qclass), file=sys.stderr)
89
90 def specificParse(config, option, value):
91 result = True
92 if option == "--type" or option == "-q":
93 config.qtype = value
94 elif option == "--class": # For Chaos, use "CHAOS", not "CH"
95 config.qclass = value
96 elif option == "--norecursive" or option == "-Z":
97 config.recursive = False
98 elif option == "--dnssec" or option == "-D":
99 config.dnssec = True
100 elif option == "--nsid":
101 config.nsid = True
102 elif option == "--ede":
103 config.ede = True
104 elif option == "--probe_id":
105 config.probe_id = True
106 elif option == "--ednssize" or option == "-B":
107 config.edns_size = int(value)
108 elif option == "--tcp":
109 config.protocol = "TCP"
110 elif option == "--tls":
111 config.tls = True
112 elif option == "--checkingdisabled" or option == "-k":
113 config.dnssec_checking = False
114 elif option == "--sort" or option == "-S":
115 config.sort = True
116 elif option == "--authority":
117 config.answer_section = False
118 config.authority_section = True
119 elif option == "--additional":
120 config.answer_section = False
121 config.additional_section = True
122 elif option == "--nameserver" or option == "-x":
123 config.nameserver = value
124 config.nameservers = config.nameserver.split(",")
125 elif option == "--displayresolvers" or option == "-l":
126 config.display_resolvers = True
127 elif option == "--displayvalidation" or option == "-j":
128 config.display_validation = True
129 elif option == "--displayrtt":
130 config.display_rtt = True
131 elif option == "--severalperprobe":
132 config.only_one_per_probe = False
133 else:
134 result = False
135 return result
136
137 args, data = config.parse("q:ZDkSx:ljB:", ["type=", "class=", "ednssize=",
138 "displayresolvers", "probe_id",
139 "displayrtt", "displayvalidation",
140 "dnssec", "nsid", "ede", "norecursive",
141 "authority", "additional",
142 "tcp", "tls", "checkingdisabled",
143 "nameserver=", "sort",
144 "severalperprobe"], specificParse,
145 usage)
146
147 if len(args) != 1:
148 usage()
149 sys.exit(1)
150
151 domainname = args[0]
152
153 if config.tls:
154 config.protocol = "TCP"
155 # We don't set the port (853) but Atlas does it for us
156
157 data["definitions"][0]["type"] = "dns"
158 del data["definitions"][0]["size"]
159 del data["definitions"][0]["port"]
160 data["definitions"][0]["query_argument"] = domainname
161 data["definitions"][0]["description"] = ("DNS resolution of %s/%s" % (domainname, config.qtype)) + data["definitions"][0]["description"]
162 data["definitions"][0]["query_class"] = config.qclass
163 data["definitions"][0]["query_type"] = config.qtype
164 if config.edns_size is not None and config.protocol == "UDP":
165 data["definitions"][0]["udp_payload_size"] = config.edns_size
166 edns_size = config.edns_size
167 if config.dnssec or config.display_validation: # https://atlas.ripe.net/docs/api/v2/reference/#!/measurements/Dns_Type_Measurement_List_POST
168 data["definitions"][0]["set_do_bit"] = True
169 if config.edns_size is None and config.protocol == "UDP":
170 edns_size = 4096
171 if config.nsid:
172 data["definitions"][0]["set_nsid_bit"] = True
173 if config.edns_size is None and config.protocol == "UDP":
174 edns_size = 1024
175 if config.ede:
176 if config.edns_size is None and config.protocol == "UDP":
177 edns_size = 1024
178 if edns_size is not None and config.protocol == "UDP":
179 data["definitions"][0]["udp_payload_size"] = edns_size
180 if not config.dnssec_checking:
181 data["definitions"][0]["set_cd_bit"] = True
182 if config.recursive:
183 data["definitions"][0]["set_rd_bit"] = True
184 else:
185 data["definitions"][0]["set_rd_bit"] = False
186 if config.tls:
187 data["definitions"][0]["tls"] = True
188 if config.probe_id:
189 data["definitions"][0]["prepend_probe_id"] = True
190 data["definitions"][0]["protocol"] = config.protocol
191 if config.verbose and config.machine_readable:
192 usage("Specify verbose *or* machine-readable output")
193 sys.exit(1)
194 if (config.display_probes or config.display_probe_asns or config.display_resolvers or config.display_rtt) and config.machine_readable:
195 usage("Display probes/probeasns/resolvers/RTT *or* machine-readable output")
196 sys.exit(1)
197
198 if config.nameserver is None:
199 config.nameservers = [None,]
200
201 description = data["definitions"][0]["description"]
202 for nameserver in config.nameservers:
203 if nameserver is None:
204 data["definitions"][0]["use_probe_resolver"] = True
205 # Exclude probes which do not have at least one working resolver
206 data["probes"][0]["tags"]["include"].append("system-resolves-a-correctly")
207 data["probes"][0]["tags"]["include"].append("system-resolves-aaaa-correctly")
208 else:
209 data["definitions"][0]["use_probe_resolver"] = False
210 data["definitions"][0]["target"] = nameserver
211 serveraddr_type = Blaeu.host_type(nameserver)
212 data["definitions"][0]["description"] = description + (" via nameserver %s" % nameserver)
213 if serveraddr_type == Host_Type.IPv6:
214 config.ipv4 = False
215 data["definitions"][0]['af'] = 6
216 if config.include is not None:
217 data["probes"][0]["tags"]["include"] = copy.copy(config.include)
218 data["probes"][0]["tags"]["include"].append("system-ipv6-works")
219 else:
220 data["probes"][0]["tags"]["include"] = ["system-ipv6-works",]
221 elif serveraddr_type == Host_Type.IPv4:
222 config.ipv4 = True
223 data["definitions"][0]['af'] = 4
224 if config.include is not None:
225 data["probes"][0]["tags"]["include"] = copy.copy(config.include)
226 data["probes"][0]["tags"]["include"].append("system-ipv4-works")
227 else:
228 data["probes"][0]["tags"]["include"] = ["system-ipv4-works",]
229 else: # Probably an host name
230 pass
231 if config.measurement_id is None:
232 if config.verbose:
233 print(data)
234 try:
235 measurement = Blaeu.Measurement(data,
236 lambda delay: sys.stderr.write(
237 "Sleeping %i seconds...\n" % delay))
238 except Blaeu.RequestSubmissionError as error:
239 print(Blaeu.format_error(error), file=sys.stderr)
240 sys.exit(1)
241 if not config.machine_readable and config.verbose:
242 print("Measurement #%s for %s/%s uses %i probes" % \
243 (measurement.id, domainname, config.qtype, measurement.num_probes))
244
245 old_measurement = measurement.id
246 results = measurement.results(wait=True)
247 else:
248 measurement = Blaeu.Measurement(data=None, id=config.measurement_id)
249 results = measurement.results(wait=False)
250 if config.verbose:
251 print("%i results from already-done measurement %s" % (len(results), measurement.id))
252 if len(results) == 0:
253 print("Warning: zero results. Measurement not terminated? May be retry later with --measurement-ID=%s ?" % (measurement.id), file=sys.stderr)
254 probes = 0
255 successes = 0
256
257 qtype_num = dns.rdatatype.from_text(config.qtype) # Raises dns.rdatatype.UnknownRdatatype if unknown
258 sets = collections.defaultdict(Set)
259 if config.display_probes:
260 probes_sets = collections.defaultdict(set)
261 if config.display_probe_asns:
262 probe_asns_sets = collections.defaultdict(set)
263 if config.display_resolvers:
264 resolvers_sets = collections.defaultdict(set)
265 for result in results:
266 probes += 1
267 probe_id = result["prb_id"]
268 if config.display_probe_asns:
269 _probe = Blaeu.ProbeCache.cache_probe_id(config.cache_probes, probe_id) if config.cache_probes else Blaeu.Probe(probe_id)
270 first_error = ""
271 probe_resolves = False
272 resolver_responds = False
273 all_timeout = True
274 if "result" in result:
275 result_set = [{'result': result['result']},]
276 elif "resultset" in result:
277 result_set = result['resultset']
278 elif "error" in result:
279 result_set = []
280 myset = []
281 if "timeout" in result['error']:
282 myset.append("TIMEOUT")
283 elif "socket" in result['error']:
284 all_timeout = False
285 myset.append("NETWORK PROBLEM WITH RESOLVER")
286 elif "TUCONNECT" in result['error']:
287 all_timeout = False
288 myset.append("TUCONNECT (may be a TLS negotiation error or a TCP connection issue)")
289 else:
290 all_timeout = False
291 myset.append("NO RESPONSE FOR UNKNOWN REASON at probe %s" % probe_id)
292 else:
293 raise Blaeu.WrongAssumption("Neither result not resultset member")
294 if len(result_set) == 0:
295 myset.sort()
296 set_str = " ".join(myset)
297 sets[set_str].total += 1
298 if config.display_probes:
299 probes_sets[set_str].add(probe_id)
300 if config.display_probe_asns:
301 probe_asns_sets[set_str].add(getattr(_probe, "asn_v%i" % (4 if config.ipv4 else 6), None))
302 for result_i in result_set:
303 try:
304 if "dst_addr" in result_i:
305 resolver = str(result_i['dst_addr'])
306 elif "dst_name" in result_i: # Apparently, used when there was a problem
307 resolver = str(result_i['dst_name'])
308 elif "dst_addr" in result: # Used when specifying a name server
309 resolver = str(result['dst_addr'])
310 elif "dst_name" in result: # Apparently, used when there was a problem
311 resolver = str(result['dst_name'])
312 else:
313 resolver = "UNKNOWN RESOLUTION ERROR"
314 myset = []
315 if "result" not in result_i:
316 if config.only_one_per_probe:
317 continue
318 else:
319 if "timeout" in result_i['error']:
320 myset.append("TIMEOUT")
321 elif "socket" in result_i['error']:
322 all_timeout = False
323 myset.append("NETWORK PROBLEM WITH RESOLVER")
324 else:
325 all_timeout = False
326 myset.append("NO RESPONSE FOR UNKNOWN REASON at probe %s" % probe_id)
327 else:
328 all_timeout = False
329 resolver_responds = True
330 answer = result_i['result']['abuf'] + "=="
331 content = base64.b64decode(answer)
332 msg = dns.message.from_wire(content)
333 if config.ede:
334 if hasattr(dns.edns, 'EDE'): # Appeared in DNS Python in 2024?
335 opt_ede = next((opt for opt in msg.options if opt.otype == dns.edns.EDE), None)
336 if opt_ede:
337 ede = opt_ede.to_text()
338 myset.append(ede)
339 if config.nsid:
340 opt_nsid = next((opt for opt in msg.options if opt.otype == dns.edns.NSID), None)
341 # dnspython handles NSID with version >=
342 # 2.6. Before that, we have to do it.
343 if opt_nsid and hasattr(opt_nsid, "data"): # < 2.6
344 nsid = opt_nsid.data.decode()
345 elif opt_nsid and hasattr(opt_nsid, "nsid"): # > 2.6
346 nsid = opt_nsid.to_text()
347 if nsid.startswith("NSID "):
348 nsid = nsid[5:] # Remove the "NSID " prefix
349 else: # NSID option not found or could not be parsed
350 nsid = None
351 myset.append("NSID: %s;" % nsid)
352 successes += 1
353 if msg.rcode() == dns.rcode.NOERROR:
354 probe_resolves = True
355 if config.answer_section:
356 if result_i['result']['ANCOUNT'] == 0 and config.verbose:
357 # If we test an authoritative server, and it returns a delegation, we won't see anything...
358 print("Warning: reply at probe %s has no answers: may be the server returned a delegation, or does not have data of type %s? For the first case, you may want to use --authority." % (probe_id, config.qtype), file=sys.stderr)
359 interesting_section = msg.answer
360 elif config.authority_section:
361 interesting_section = msg.authority
362 elif config.additional_section:
363 interesting_section = msg.additional
364 for rrset in interesting_section:
365 for rdata in rrset:
366 if rdata.rdtype == qtype_num:
367 myset.append(str(rdata)[0:MAXLEN].lower()) # We truncate because DNSKEY can be very long
368 if config.display_validation and (msg.flags & dns.flags.AD):
369 myset.append(" (Authentic Data flag) ")
370 if (msg.flags & dns.flags.TC):
371 if edns_size is not None:
372 myset.append(" (TRUNCATED - EDNS buffer size was %d ) " % edns_size)
373 else:
374 myset.append(" (TRUNCATED - May have to use --ednssize) ")
375 else:
376 if msg.rcode() == dns.rcode.REFUSED: # Not SERVFAIL since
377 # it can be legitimate (DNSSEC problem, for instance)
378 if config.only_one_per_probe and len(result_set) > 1: # It
379 # does not handle the case where there
380 # are several resolvers and all say
381 # REFUSED (probably a rare case).
382 if first_error == "":
383 first_error = "ERROR: %s" % dns.rcode.to_text(msg.rcode())
384 continue # Try again
385 else:
386 probe_resolves = True # NXDOMAIN or SERVFAIL are legitimate
387 myset.append("ERROR: %s" % dns.rcode.to_text(msg.rcode()))
388 myset.sort() # Not ideal since the alphabetical sort
389 # will, for instance, put EDE before
390 # ERROR. We should create myset more
391 # intelligently.
392 set_str = " ".join(myset)
393 sets[set_str].total += 1
394 if "error" not in result_i:
395 sets[set_str].successes += 1
396 if config.display_probes:
397 probes_sets[set_str].add(probe_id)
398 if config.display_probe_asns:
399 _res_af = result_i.get("af") or result.get("af")
400 if _res_af:
401 probe_asns_sets[set_str].add(getattr(_probe, "asn_v%i" % _res_af))
402 if config.display_resolvers:
403 resolvers_sets[set_str].add(resolver)
404 if config.display_rtt:
405 if "error" not in result_i:
406 if "result" not in result_i:
407 sets[set_str].rtt += result_i['rt']
408 else:
409 sets[set_str].rtt += result_i['result']['rt']
410 except dns.name.BadLabelType:
411 if not config.machine_readable:
412 print("Probe %s failed (bad label in name)" % probe_id, file=sys.stderr)
413 except dns.message.TrailingJunk:
414 if not config.machine_readable:
415 print("Probe %s failed (trailing junk)" % probe_id, file=sys.stderr)
416 except dns.exception.FormError:
417 if not config.machine_readable:
418 print("Probe %s failed (malformed DNS message)" % probe_id, file=sys.stderr)
419 if config.only_one_per_probe:
420 break
421 if not probe_resolves and first_error != "" and config.verbose:
422 print("Warning, probe %s has no working resolver (first error is \"%s\")" % (probe_id, first_error), file=sys.stderr)
423 if not resolver_responds:
424 if all_timeout and not config.only_one_per_probe:
425 if config.verbose:
426 print("Warning, probe %s never got reply from any resolver" % (probe_id), file=sys.stderr)
427 set_str = "TIMEOUT(S) on all resolvers"
428 sets[set_str].total += 1
429 else:
430 myset.sort()
431 set_str = " ".join(myset)
432 if config.sort:
433 sets_data = sorted(sets, key=lambda s: sets[s].total, reverse=True)
434 else:
435 sets_data = sets
436 details = []
437 if not config.machine_readable and config.nameserver is not None:
438 print("Nameserver %s" % nameserver)
439 if not config.answer_section:
440 if config.authority_section:
441 print("Authority section of the DNS responses")
442 elif config.additional_section:
443 print("Additional section of the DNS responses")
444 else:
445 print("INTERNAL PROBLEM: no section to display?")
446 for myset in sets_data:
447 detail = ""
448 if config.display_probes:
449 detail = "(probes %s)" % probes_sets[myset]
450 if config.display_probe_asns:
451 detail = "(probe asns %s)" % probe_asns_sets[myset]
452 if config.display_resolvers:
453 detail += "(resolvers %s)" % resolvers_sets[myset]
454 if config.display_rtt and sets[myset].successes > 0:
455 detail += "Average RTT %i ms" % (sets[myset].rtt/sets[myset].successes)
456 if not config.machine_readable:
457 print("[%s] : %i occurrences %s" % (myset, sets[myset].total, detail))
458 else:
459 details.append("[%s];%i" % (myset, sets[myset].total))
460
461 if not config.machine_readable:
462 print(("Test #%s done at %s" % (measurement.id, time.strftime("%Y-%m-%dT%H:%M:%SZ", measurement.time))))
463 print(f"Results on atlas.ripe.net : https://atlas.ripe.net/measurements/{measurement.id}")
464 print("")
465 else:
466 if config.nameserver is None:
467 ns = "DEFAULT RESOLVER"
468 else:
469 ns = config.nameserver
470 print(",".join([domainname, config.qtype, str(measurement.id), "%s/%s" % (len(results), measurement.num_probes), \
471 time.strftime("%Y-%m-%dT%H:%M:%SZ", measurement.time), ns] + details))