Debian Codegraph @

ansible_collections/community/general/plugins/lookup/dig.py

raw
1 # Copyright (c) 2015, Jan-Piet Mens <jpmens(at)gmail.com>
2 # Copyright (c) 2017 Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5 from __future__ import annotations
6
7 DOCUMENTATION = r"""
8 name: dig
9 author: Jan-Piet Mens (@jpmens) <jpmens(at)gmail.com>
10 short_description: Query DNS using the dnspython library
11 requirements:
12 - dnspython (python library, http://www.dnspython.org/)
13 description:
14 - The dig lookup runs queries against DNS servers to retrieve DNS records for a specific name (FQDN - fully qualified domain
15 name). It is possible to lookup any DNS record in this manner.
16 - There is a couple of different syntaxes that can be used to specify what record should be retrieved, and for which name.
17 It is also possible to explicitly specify the DNS server(s) to use for lookups.
18 - In its simplest form, the dig lookup plugin can be used to retrieve an IPv4 address (DNS A record) associated with FQDN.
19 - In addition to (default) A record, it is also possible to specify a different record type that should be queried. This
20 can be done by either passing-in additional parameter of format qtype=TYPE to the dig lookup, or by appending /TYPE to
21 the FQDN being queried.
22 - If multiple values are associated with the requested record, the results are returned as a comma-separated list. In
23 such cases you may want to pass option C(wantlist=true) to the lookup call, or alternatively use C(query) instead of C(lookup),
24 which results in the record values being returned as a list over which you can iterate later on.
25 - By default, the lookup relies on system-wide configured DNS servers for performing the query. It is also possible to
26 explicitly specify DNS servers to query using the @DNS_SERVER_1,DNS_SERVER_2,...,DNS_SERVER_N notation. This needs to
27 be passed-in as an additional parameter to the lookup.
28 options:
29 _terms:
30 description: Domain(s) to query.
31 type: list
32 elements: str
33 qtype:
34 description:
35 - Record type to query.
36 - V(DLV) has been removed in community.general 6.0.0.
37 - V(CAA) has been added in community.general 6.3.0.
38 type: str
39 default: 'A'
40 choices:
41 - A
42 - ALL
43 - AAAA
44 - CAA
45 - CNAME
46 - DNAME
47 - DNSKEY
48 - DS
49 - HINFO
50 - LOC
51 - MX
52 - NAPTR
53 - NS
54 - NSEC3PARAM
55 - PTR
56 - RP
57 - RRSIG
58 - SOA
59 - SPF
60 - SRV
61 - SSHFP
62 - TLSA
63 - TXT
64 flat:
65 description: If 0 each record is returned as a dictionary, otherwise a string.
66 type: int
67 default: 1
68 retry_servfail:
69 description: Retry a nameserver if it returns SERVFAIL.
70 default: false
71 type: bool
72 version_added: 3.6.0
73 fail_on_error:
74 description:
75 - Abort execution on lookup errors.
76 - The default for this option is likely to change to V(true) in the future. The current default, V(false), is used for
77 backwards compatibility, and results in empty strings or the string V(NXDOMAIN) in the result in case of errors.
78 default: false
79 type: bool
80 version_added: 5.4.0
81 real_empty:
82 description:
83 - Return empty result without empty strings, and return empty list instead of V(NXDOMAIN).
84 - The default for this option is likely to change to V(true) in the future.
85 - This option is forced to V(true) if multiple domains to be queried are specified.
86 default: false
87 type: bool
88 version_added: 6.0.0
89 class:
90 description:
91 - Class.
92 type: str
93 default: 'IN'
94 tcp:
95 description: Use TCP to lookup DNS records.
96 default: false
97 type: bool
98 version_added: 7.5.0
99 port:
100 description: Use port as target port when looking up DNS records.
101 default: 53
102 type: int
103 version_added: 9.5.0
104 notes:
105 - V(ALL) is not a record in itself, merely the listed fields are available for any record results you retrieve in the form
106 of a dictionary.
107 - While the plugin supports anything which C(dnspython) supports out of the box, only a subset can be converted into a dictionary.
108 - If you need to obtain the AAAA record (IPv6 address), you must specify the record type explicitly. Syntax for specifying
109 the record type is shown in the examples below.
110 - The trailing dot in most of the examples listed is purely optional, but is specified for completeness/correctness sake.
111 """
112
113 EXAMPLES = r"""
114 - name: Simple A record (IPV4 address) lookup for example.com
115 ansible.builtin.debug:
116 msg: "{{ lookup('community.general.dig', 'example.com.')}}"
117
118 - name: "The TXT record for example.org."
119 ansible.builtin.debug:
120 msg: "{{ lookup('community.general.dig', 'example.org.', qtype='TXT') }}"
121
122 - name: "The TXT record for example.org, alternative syntax."
123 ansible.builtin.debug:
124 msg: "{{ lookup('community.general.dig', 'example.org./TXT') }}"
125
126 - name: use in a loop
127 ansible.builtin.debug:
128 msg: "MX record for gmail.com {{ item }}"
129 with_items: "{{ lookup('community.general.dig', 'gmail.com./MX', wantlist=true) }}"
130
131 - name: Lookup multiple names at once
132 ansible.builtin.debug:
133 msg: "A record found {{ item }}"
134 loop: "{{ query('community.general.dig', 'example.org.', 'example.com.', 'gmail.com.') }}"
135
136 - name: Lookup multiple names at once (from list variable)
137 ansible.builtin.debug:
138 msg: "A record found {{ item }}"
139 loop: "{{ query('community.general.dig', *hosts) }}"
140 vars:
141 hosts:
142 - example.org.
143 - example.com.
144 - gmail.com.
145
146 - ansible.builtin.debug:
147 msg: "Reverse DNS for 192.0.2.5 is {{ lookup('community.general.dig', '192.0.2.5/PTR') }}"
148 - ansible.builtin.debug:
149 msg: "Reverse DNS for 192.0.2.5 is {{ lookup('community.general.dig', '5.2.0.192.in-addr.arpa./PTR') }}"
150 - ansible.builtin.debug:
151 msg: "Reverse DNS for 192.0.2.5 is {{ lookup('community.general.dig', '5.2.0.192.in-addr.arpa.', qtype='PTR') }}"
152 - ansible.builtin.debug:
153 msg: "Querying 198.51.100.23 for IPv4 address for example.com. produces {{ lookup('dig', 'example.com', '@198.51.100.23') }}"
154
155 - ansible.builtin.debug:
156 msg: "XMPP service for gmail.com. is available at {{ item.target }} on port {{ item.port }}"
157 with_items: "{{ lookup('community.general.dig', '_xmpp-server._tcp.gmail.com./SRV', flat=0, wantlist=true) }}"
158
159 - name: Retry nameservers that return SERVFAIL
160 ansible.builtin.debug:
161 msg: "{{ lookup('community.general.dig', 'example.org./A', retry_servfail=true) }}"
162 """
163
164 RETURN = r"""
165 _list:
166 description:
167 - List of composed strings or of dictionaries, with fields depending
168 on query type.
169 type: list
170 elements: raw
171 contains:
172 ALL:
173 description:
174 - C(owner), C(ttl), C(type).
175 A:
176 description:
177 - C(address).
178 AAAA:
179 description:
180 - C(address).
181 CAA:
182 description:
183 - C(flags).
184 - C(tag).
185 - C(value).
186 version_added: 6.3.0
187 CNAME:
188 description:
189 - C(target).
190 DNAME:
191 description:
192 - C(target).
193 DNSKEY:
194 description:
195 - C(flags), C(algorithm), C(protocol), C(key).
196 DS:
197 description:
198 - C(algorithm), C(digest_type), C(key_tag), C(digest).
199 HINFO:
200 description:
201 - C(cpu), C(os).
202 LOC:
203 description:
204 - C(latitude), C(longitude), C(altitude), C(size), C(horizontal_precision), C(vertical_precision).
205 MX:
206 description:
207 - C(preference), C(exchange).
208 NAPTR:
209 description:
210 - C(order), C(preference), C(flags), C(service), C(regexp), C(replacement).
211 NS:
212 description:
213 - C(target).
214 NSEC3PARAM:
215 description:
216 - C(algorithm), C(flags), C(iterations), C(salt).
217 PTR:
218 description:
219 - C(target).
220 RP:
221 description:
222 - C(mbox), C(txt).
223 SOA:
224 description:
225 - C(mname), C(rname), C(serial), C(refresh), C(retry), C(expire), C(minimum).
226 SPF:
227 description:
228 - C(strings).
229 SRV:
230 description:
231 - C(priority), C(weight), C(port), C(target).
232 SSHFP:
233 description:
234 - C(algorithm), C(fp_type), C(fingerprint).
235 TLSA:
236 description:
237 - C(usage), C(selector), C(mtype), C(cert).
238 TXT:
239 description:
240 - C(strings).
241 """
242
243 import socket
244
245 from ansible.errors import AnsibleError
246 from ansible.module_utils.parsing.convert_bool import boolean
247 from ansible.plugins.lookup import LookupBase
248 from ansible.utils.display import Display
249
250 from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
251
252 try:
253 import dns.exception
254 import dns.name
255 import dns.rdataclass
256 import dns.resolver
257 import dns.reversename
258 from dns.rdatatype import (
259 AAAA,
260 CAA,
261 CNAME,
262 DNAME,
263 DNSKEY,
264 DS,
265 HINFO,
266 LOC,
267 MX,
268 NAPTR,
269 NS,
270 NSEC3PARAM,
271 PTR,
272 RP,
273 SOA,
274 SPF,
275 SRV,
276 SSHFP,
277 TLSA,
278 TXT,
279 A,
280 )
281
282 HAVE_DNS = True
283 except ImportError:
284 HAVE_DNS = False
285
286
287 display = Display()
288
289
290 def make_rdata_dict(rdata):
291 """While the 'dig' lookup plugin supports anything which dnspython supports
292 out of the box, the following supported_types list describes which
293 DNS query types we can convert to a dict.
294
295 Note: adding support for RRSIG is hard work. :)
296 """
297 supported_types = {
298 A: ["address"],
299 AAAA: ["address"],
300 CAA: ["flags", "tag", "value"],
301 CNAME: ["target"],
302 DNAME: ["target"],
303 DNSKEY: ["flags", "algorithm", "protocol", "key"],
304 DS: ["algorithm", "digest_type", "key_tag", "digest"],
305 HINFO: ["cpu", "os"],
306 LOC: ["latitude", "longitude", "altitude", "size", "horizontal_precision", "vertical_precision"],
307 MX: ["preference", "exchange"],
308 NAPTR: ["order", "preference", "flags", "service", "regexp", "replacement"],
309 NS: ["target"],
310 NSEC3PARAM: ["algorithm", "flags", "iterations", "salt"],
311 PTR: ["target"],
312 RP: ["mbox", "txt"],
313 # RRSIG: ['type_covered', 'algorithm', 'labels', 'original_ttl', 'expiration', 'inception', 'key_tag', 'signer', 'signature'],
314 SOA: ["mname", "rname", "serial", "refresh", "retry", "expire", "minimum"],
315 SPF: ["strings"],
316 SRV: ["priority", "weight", "port", "target"],
317 SSHFP: ["algorithm", "fp_type", "fingerprint"],
318 TLSA: ["usage", "selector", "mtype", "cert"],
319 TXT: ["strings"],
320 }
321
322 rd = {}
323
324 if rdata.rdtype in supported_types:
325 fields = supported_types[rdata.rdtype]
326 for f in fields:
327 val = rdata.__getattribute__(f)
328
329 if isinstance(val, dns.name.Name):
330 val = dns.name.Name.to_text(val)
331
332 if rdata.rdtype == DS and f == "digest":
333 val = dns.rdata._hexify(rdata.digest).replace(" ", "")
334 if rdata.rdtype == DNSKEY and f == "algorithm":
335 val = int(val)
336 if rdata.rdtype == DNSKEY and f == "key":
337 val = dns.rdata._base64ify(rdata.key).replace(" ", "")
338 if rdata.rdtype == NSEC3PARAM and f == "salt":
339 val = dns.rdata._hexify(rdata.salt).replace(" ", "")
340 if rdata.rdtype == SSHFP and f == "fingerprint":
341 val = dns.rdata._hexify(rdata.fingerprint).replace(" ", "")
342 if rdata.rdtype == TLSA and f == "cert":
343 val = dns.rdata._hexify(rdata.cert).replace(" ", "")
344
345 rd[f] = val
346
347 return rd
348
349
350 # ==============================================================
351 # dig: Lookup DNS records
352 #
353 # --------------------------------------------------------------
354
355
356 class LookupModule(LookupBase):
357 def run(self, terms, variables=None, **kwargs):
358 """
359 terms contains a string with things to `dig' for. We support the
360 following formats:
361 example.com # A record
362 example.com qtype=A # same
363 example.com/TXT # specific qtype
364 example.com qtype=txt # same
365 192.0.2.23/PTR # reverse PTR
366 ^^ shortcut for 23.2.0.192.in-addr.arpa/PTR
367 example.net/AAAA @nameserver # query specified server
368 ^^^ can be comma-sep list of names/addresses
369
370 ... flat=0 # returns a dict; default is 1 == string
371 """
372 if HAVE_DNS is False:
373 raise AnsibleError("The dig lookup requires the python 'dnspython' library and it is not installed")
374
375 self.set_options(var_options=variables, direct=kwargs)
376 check_for_wrong_terms(self, direct=kwargs)
377
378 # Create Resolver object so that we can set NS if necessary
379 myres = dns.resolver.Resolver(configure=True)
380 edns_size = 4096
381 myres.use_edns(0, ednsflags=dns.flags.DO, payload=edns_size)
382
383 domains = []
384 nameservers = []
385 qtype = self.get_option("qtype")
386 flat = self.get_option("flat")
387 fail_on_error = self.get_option("fail_on_error")
388 real_empty = self.get_option("real_empty")
389 tcp = self.get_option("tcp")
390 port = self.get_option("port")
391 try:
392 rdclass = dns.rdataclass.from_text(self.get_option("class"))
393 except Exception as e:
394 raise AnsibleError(f"dns lookup illegal CLASS: {e}") from e
395 myres.retry_servfail = self.get_option("retry_servfail")
396
397 for t in terms:
398 if t.startswith("@"): # e.g. "@10.0.1.2,192.0.2.1" is ok.
399 nsset = t[1:].split(",")
400 for ns in nsset:
401 # Check if we have a valid IP address. If so, use that, otherwise
402 # try to resolve name to address using system's resolver. If that
403 # fails we bail out.
404 try:
405 socket.inet_aton(ns)
406 nameservers.append(ns)
407 except Exception:
408 try:
409 nsaddr = dns.resolver.query(ns)[0].address
410 nameservers.append(nsaddr)
411 except Exception as e:
412 raise AnsibleError(f"dns lookup NS: {e}") from e
413 continue
414 if "=" in t:
415 try:
416 opt, arg = t.split("=", 1)
417 except Exception:
418 pass
419
420 if opt == "qtype":
421 qtype = arg.upper()
422 elif opt == "flat":
423 flat = int(arg)
424 elif opt == "class":
425 try:
426 rdclass = dns.rdataclass.from_text(arg)
427 except Exception as e:
428 raise AnsibleError(f"dns lookup illegal CLASS: {e}") from e
429 elif opt == "retry_servfail":
430 myres.retry_servfail = boolean(arg)
431 elif opt == "fail_on_error":
432 fail_on_error = boolean(arg)
433 elif opt == "real_empty":
434 real_empty = boolean(arg)
435 elif opt == "tcp":
436 tcp = boolean(arg)
437
438 continue
439
440 if "/" in t:
441 try:
442 domain, qtype = t.split("/")
443 domains.append(domain)
444 except Exception:
445 domains.append(t)
446 else:
447 domains.append(t)
448
449 # print "--- domain = {domain} qtype={qtype} rdclass={rdclass}"
450
451 if port:
452 myres.port = port
453 if len(nameservers) > 0:
454 myres.nameservers = nameservers
455
456 if qtype.upper() == "PTR":
457 reversed_domains = []
458 for domain in domains:
459 try:
460 n = dns.reversename.from_address(domain)
461 reversed_domains.append(n.to_text())
462 except dns.exception.SyntaxError:
463 pass
464 except Exception as e:
465 raise AnsibleError(f"dns.reversename unhandled exception {e}") from e
466 domains = reversed_domains
467
468 if len(domains) > 1:
469 real_empty = True
470
471 ret = []
472
473 for domain in domains:
474 try:
475 answers = myres.query(domain, qtype, rdclass=rdclass, tcp=tcp)
476 for rdata in answers:
477 s = rdata.to_text()
478 if qtype.upper() == "TXT":
479 s = s[1:-1] # Strip outside quotes on TXT rdata
480
481 if flat:
482 ret.append(s)
483 else:
484 try:
485 rd = make_rdata_dict(rdata)
486 rd["owner"] = answers.canonical_name.to_text()
487 rd["type"] = dns.rdatatype.to_text(rdata.rdtype)
488 rd["ttl"] = answers.rrset.ttl
489 rd["class"] = dns.rdataclass.to_text(rdata.rdclass)
490
491 ret.append(rd)
492 except Exception as err:
493 if fail_on_error:
494 raise AnsibleError(f"Lookup failed: {err}") from err
495 ret.append(str(err))
496
497 except dns.resolver.NXDOMAIN as err:
498 if fail_on_error:
499 raise AnsibleError(f"Lookup failed: {err}") from err
500 if not real_empty:
501 ret.append("NXDOMAIN")
502 except (dns.resolver.NoAnswer, dns.resolver.Timeout, dns.resolver.NoNameservers) as err:
503 if fail_on_error:
504 raise AnsibleError(f"Lookup failed: {err}") from err
505 if not real_empty:
506 ret.append("")
507 except dns.exception.DNSException as err:
508 raise AnsibleError(f"dns.resolver unhandled exception {err}") from err
509
510 return ret