Debian Codegraph @

ansible_collections/community/general/plugins/modules/nsupdate.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2016, Marcin Skarbek <[email protected]>
4 # Copyright (c) 2016, Andreas Olsson <[email protected]>
5 # Copyright (c) 2017, Loic Blot <[email protected]>
6 #
7 # This module was ported from https://github.com/mskarbek/ansible-nsupdate
8 #
9 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
10 # SPDX-License-Identifier: GPL-3.0-or-later
11
12 from __future__ import annotations
13
14 DOCUMENTATION = r"""
15 module: nsupdate
16
17 short_description: Manage DNS records
18 description:
19 - Create, update and remove DNS records using DDNS updates.
20 requirements:
21 - dnspython
22 - gssapi (when using GSS-TSIG authentication)
23 author: "Loic Blot (@nerzhul)"
24 extends_documentation_fragment:
25 - community.general._attributes
26 attributes:
27 check_mode:
28 support: full
29 diff_mode:
30 support: none
31 options:
32 state:
33 description:
34 - Manage DNS record.
35 choices: ['present', 'absent']
36 default: 'present'
37 type: str
38 server:
39 description:
40 - Apply DNS modification on this server, specified by IPv4/IPv6 address or FQDN.
41 - FQDNs are supported since community.general 12.3.0.
42 required: true
43 type: str
44 port:
45 description:
46 - Use this TCP port when connecting to O(server).
47 default: 53
48 type: int
49 key_name:
50 description:
51 - Use TSIG key name to authenticate against DNS O(server).
52 - Not required when using O(key_algorithm=gss-tsig).
53 type: str
54 key_secret:
55 description:
56 - Use TSIG key secret, associated with O(key_name), to authenticate against O(server).
57 - Not required when using O(key_algorithm=gss-tsig).
58 type: str
59 key_algorithm:
60 description:
61 - Specify key algorithm used by O(key_secret).
62 - Use V(gss-tsig) for GSS-TSIG authentication (requires the gssapi library and Kerberos credentials).
63 - V(gss-tsig) was added in community.general 12.3.0.
64 choices: ['HMAC-MD5.SIG-ALG.REG.INT', 'hmac-md5', 'hmac-sha1', 'hmac-sha224', 'hmac-sha256', 'hmac-sha384', 'hmac-sha512', 'gss-tsig']
65 default: 'hmac-md5'
66 type: str
67 zone:
68 description:
69 - DNS record is modified on this O(zone).
70 - When omitted, DNS is queried to attempt finding the correct zone.
71 type: str
72 record:
73 description:
74 - Sets the DNS record to modify. When zone is omitted this has to be absolute (ending with a dot).
75 required: true
76 type: str
77 type:
78 description:
79 - Sets the record type.
80 default: 'A'
81 type: str
82 ttl:
83 description:
84 - Sets the record TTL.
85 default: 3600
86 type: int
87 value:
88 description:
89 - Sets the record value.
90 type: list
91 elements: str
92 protocol:
93 description:
94 - Sets the transport protocol (TCP or UDP). TCP is the recommended and a more robust option.
95 default: 'tcp'
96 choices: ['tcp', 'udp']
97 type: str
98 timeout:
99 description:
100 - Timeout in seconds for each DNS query sent to O(server).
101 default: 10
102 type: float
103 version_added: 13.0.0
104 """
105
106 EXAMPLES = r"""
107 - name: Add or modify ansible.example.org A to 192.168.1.1"
108 community.general.nsupdate:
109 key_name: "nsupdate"
110 key_secret: "+bFQtBCta7j2vWkjPkAFtgA=="
111 server: "10.1.1.1"
112 zone: "example.org"
113 record: "ansible"
114 value: "192.168.1.1"
115
116 - name: Add or modify ansible.example.org A to 192.168.1.1, 192.168.1.2 and 192.168.1.3"
117 community.general.nsupdate:
118 key_name: "nsupdate"
119 key_secret: "+bFQtBCta7j2vWkjPkAFtgA=="
120 server: "10.1.1.1"
121 zone: "example.org"
122 record: "ansible"
123 value: ["192.168.1.1", "192.168.1.2", "192.168.1.3"]
124
125 - name: Remove puppet.example.org CNAME
126 community.general.nsupdate:
127 key_name: "nsupdate"
128 key_secret: "+bFQtBCta7j2vWkjPkAFtgA=="
129 server: "10.1.1.1"
130 zone: "example.org"
131 record: "puppet"
132 type: "CNAME"
133 state: absent
134
135 - name: Add 1.1.168.192.in-addr.arpa. PTR for ansible.example.org
136 community.general.nsupdate:
137 key_name: "nsupdate"
138 key_secret: "+bFQtBCta7j2vWkjPkAFtgA=="
139 server: "10.1.1.1"
140 record: "1.1.168.192.in-addr.arpa."
141 type: "PTR"
142 value: "ansible.example.org."
143 state: present
144
145 - name: Remove 1.1.168.192.in-addr.arpa. PTR
146 community.general.nsupdate:
147 key_name: "nsupdate"
148 key_secret: "+bFQtBCta7j2vWkjPkAFtgA=="
149 server: "10.1.1.1"
150 record: "1.1.168.192.in-addr.arpa."
151 type: "PTR"
152 state: absent
153
154 - name: Use FQDN for server instead of IP address
155 community.general.nsupdate:
156 key_name: "nsupdate"
157 key_secret: "+bFQtBCta7j2vWkjPkAFtgA=="
158 server: "ns1.example.org"
159 zone: "example.org"
160 record: "ansible"
161 value: "192.168.1.1"
162
163 - name: Use GSS-TSIG authentication (requires Kerberos credentials)
164 community.general.nsupdate:
165 key_algorithm: "gss-tsig"
166 server: "ns1.example.org"
167 zone: "example.org"
168 record: "ansible"
169 value: "192.168.1.1"
170 """
171
172 RETURN = r"""
173 record:
174 description: DNS record.
175 returned: success
176 type: str
177 sample: 'ansible'
178 ttl:
179 description: DNS record TTL.
180 returned: success
181 type: int
182 sample: 86400
183 type:
184 description: DNS record type.
185 returned: success
186 type: str
187 sample: 'CNAME'
188 value:
189 description: DNS record value(s).
190 returned: success
191 type: list
192 sample: '192.168.1.1'
193 zone:
194 description: DNS record zone.
195 returned: success
196 type: str
197 sample: 'example.org.'
198 dns_rc:
199 description: C(dnspython) return code.
200 returned: always
201 type: int
202 sample: 4
203 dns_rc_str:
204 description: C(dnspython) return code (string representation).
205 returned: always
206 type: str
207 sample: 'REFUSED'
208 """
209
210 import ipaddress
211 import time
212 import uuid
213 from binascii import Error as binascii_error
214 from contextlib import suppress
215
216 from ansible.module_utils.basic import AnsibleModule
217
218 from ansible_collections.community.general.plugins.module_utils import _deps as deps
219
220 with deps.declare("dnspython", url="https://github.com/rthalley/dnspython"):
221 import dns.message
222 import dns.query
223 import dns.rdtypes.ANY.TKEY
224 import dns.resolver
225 import dns.tsigkeyring
226 import dns.update
227
228 with deps.declare("gssapi", reason="for gss-tsig keys", url="https://github.com/pythongssapi/python-gssapi"):
229 import gssapi
230
231
232 class RecordManager:
233 def __init__(self, module):
234 self.module = module
235
236 self.server_fqdn = None
237 self.server_ips = self.resolve_server()
238 self.keyring = None
239 self.keyname = None
240
241 if module.params["key_algorithm"] == "hmac-md5":
242 self.algorithm = "HMAC-MD5.SIG-ALG.REG.INT"
243 elif module.params["key_algorithm"] == "gss-tsig":
244 if module.params["key_name"]:
245 self.module.fail_json(msg="key_name cannot be used with GSS-TSIG")
246 self.algorithm = dns.tsig.GSS_TSIG
247 self.keyring, self.keyname = self.init_gssapi()
248 else:
249 self.algorithm = module.params["key_algorithm"]
250
251 if module.params["key_name"]:
252 try:
253 self.keyring = dns.tsigkeyring.from_text({module.params["key_name"]: module.params["key_secret"]})
254 self.keyname = module.params["key_name"]
255 except TypeError:
256 module.fail_json(msg="Missing key_secret")
257 except binascii_error as e:
258 module.fail_json(msg=f"TSIG key error: {e}")
259
260 if module.params["zone"] is None:
261 if module.params["record"][-1] != ".":
262 self.module.fail_json(msg="record must be absolute when omitting zone parameter")
263 self.zone = self.lookup_zone()
264 else:
265 self.zone = module.params["zone"]
266
267 if self.zone[-1] != ".":
268 self.zone += "."
269
270 if module.params["record"][-1] != ".":
271 self.fqdn = f"{module.params['record']}.{self.zone}"
272 else:
273 self.fqdn = module.params["record"]
274
275 if self.module.params["type"].lower() == "txt" and self.module.params["value"] is not None:
276 self.value = [self.txt_helper(x) for x in self.module.params["value"]]
277 else:
278 self.value = self.module.params["value"]
279
280 self.dns_rc = 0
281
282 def resolve_server(self):
283 """Resolve server parameter to a list of IP addresses if it's a FQDN."""
284 server = self.module.params["server"]
285
286 # Check if it's already an IPv4/IPv6 address
287 try:
288 ipaddress.ip_address(server)
289 return [server]
290 except ValueError:
291 pass
292
293 # Try to resolve the FQDN
294 try:
295 resolver = dns.resolver.Resolver()
296 name = dns.name.from_text(server)
297 ip_list = []
298
299 with suppress(dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
300 answers = resolver.resolve(name, dns.rdatatype.AAAA)
301 self.server_fqdn = server
302 ip_list.extend([str(answer) for answer in answers])
303
304 with suppress(dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
305 answers = resolver.resolve(name, dns.rdatatype.A)
306 self.server_fqdn = server
307 ip_list.extend([str(answer) for answer in answers])
308
309 if not ip_list:
310 self.module.fail_json(msg=f"Failed to resolve server '{server}' to an IP address")
311
312 return ip_list
313
314 except dns.exception.DNSException as e:
315 self.module.fail_json(msg=f"DNS resolution error for server '{server}': {e}")
316
317 def query(self, query):
318 last_exception = None
319 timeout = self.module.params["timeout"]
320 for server_ip in self.server_ips:
321 try:
322 if self.module.params["protocol"] == "tcp":
323 return dns.query.tcp(query, server_ip, timeout=timeout, port=self.module.params["port"])
324 else:
325 return dns.query.udp(query, server_ip, timeout=timeout, port=self.module.params["port"])
326 except (OSError, dns.exception.Timeout) as e:
327 last_exception = e
328 continue
329
330 # If all servers failed, raise the last exception
331 if last_exception:
332 raise last_exception
333
334 def build_tkey_query(self, token, key_ring, key_name):
335 inception_time = int(time.time())
336 tkey = dns.rdtypes.ANY.TKEY.TKEY(
337 dns.rdataclass.ANY,
338 dns.rdatatype.TKEY,
339 dns.tsig.GSS_TSIG,
340 inception_time,
341 inception_time,
342 3,
343 dns.rcode.NOERROR,
344 token,
345 b"",
346 )
347
348 query = dns.message.make_query(key_name, dns.rdatatype.TKEY, dns.rdataclass.ANY)
349 query.keyring = key_ring
350 query.find_rrset(dns.message.ADDITIONAL, key_name, dns.rdataclass.ANY, dns.rdatatype.TKEY, create=True).add(
351 tkey
352 )
353 return query
354
355 def init_gssapi(self):
356 deps.validate(self.module, "gssapi")
357 if not self.server_fqdn:
358 self.module.fail_json(msg="server must be a FQDN")
359
360 # Acquire GSSAPI credentials
361 gss_name = gssapi.Name(f"DNS@{self.server_fqdn}", gssapi.NameType.hostbased_service)
362 try:
363 gss_ctx = gssapi.SecurityContext(name=gss_name, usage="initiate")
364 except gssapi.exceptions.GSSError as e:
365 self.module.fail_json(msg=f"GSSAPI context initialization error: {e}")
366
367 # Generate unique key name
368 keyname = dns.name.from_text(f"{uuid.uuid4()}.{self.server_fqdn}")
369 tsig_key = dns.tsig.Key(keyname, gss_ctx, dns.tsig.GSS_TSIG)
370 keyring = dns.tsig.GSSTSigAdapter({keyname: tsig_key})
371
372 # Perform GSS-TSIG negotiation
373 token = gss_ctx.step()
374 while not gss_ctx.complete:
375 tkey_query = self.build_tkey_query(token, keyring, keyname)
376 try:
377 response = self.query(tkey_query)
378 except (OSError, dns.exception.Timeout) as e:
379 self.module.fail_json(msg=f"GSS-TSIG negotiation error: ({e.__class__.__name__}): {e}")
380 if not gss_ctx.complete:
381 token = gss_ctx.step(response.answer[0][0].key)
382
383 return (keyring, keyname)
384
385 def txt_helper(self, entry):
386 if entry[0] == '"' and entry[-1] == '"':
387 return entry
388 return f'"{entry}"'
389
390 def lookup_zone(self):
391 name = dns.name.from_text(self.module.params["record"])
392 while True:
393 query = dns.message.make_query(name, dns.rdatatype.SOA)
394 if self.keyring:
395 query.use_tsig(keyring=self.keyring, keyname=self.keyname, algorithm=self.algorithm)
396 try:
397 lookup = self.query(query)
398 except (dns.tsig.PeerBadKey, dns.tsig.PeerBadSignature) as e:
399 self.module.fail_json(msg=f"TSIG update error ({e.__class__.__name__}): {e}")
400 except (OSError, dns.exception.Timeout) as e:
401 self.module.fail_json(msg=f"DNS server error: ({e.__class__.__name__}): {e}")
402 if lookup.rcode() in [dns.rcode.SERVFAIL, dns.rcode.REFUSED]:
403 self.module.fail_json(
404 msg=f"Zone lookup failure: '{self.module.params['server']}' will not "
405 f"respond to queries regarding '{self.module.params['record']}'."
406 )
407 # If the response contains an Answer SOA RR whose name matches the queried name,
408 # this is the name of the zone in which the record needs to be inserted.
409 for rr in lookup.answer:
410 if rr.rdtype == dns.rdatatype.SOA and rr.name == name:
411 return rr.name.to_text()
412 # If the response contains an Authority SOA RR whose name is a subdomain of the queried name,
413 # this SOA name is the zone in which the record needs to be inserted.
414 for rr in lookup.authority:
415 if rr.rdtype == dns.rdatatype.SOA and name.fullcompare(rr.name)[0] == dns.name.NAMERELN_SUBDOMAIN:
416 return rr.name.to_text()
417 try:
418 name = name.parent()
419 except dns.name.NoParent:
420 self.module.fail_json(msg=f"Zone lookup of '{self.module.params['record']}' failed for unknown reason.")
421
422 def __do_update(self, update):
423 response = None
424 try:
425 response = self.query(update)
426 except (dns.tsig.PeerBadKey, dns.tsig.PeerBadSignature) as e:
427 self.module.fail_json(msg=f"TSIG update error ({e.__class__.__name__}): {e}")
428 except (OSError, dns.exception.Timeout) as e:
429 self.module.fail_json(msg=f"DNS server error: ({e.__class__.__name__}): {e}")
430 return response
431
432 def create_or_update_record(self):
433 result = {"changed": False, "failed": False}
434
435 exists = self.record_exists()
436 if exists in [0, 2]:
437 if self.module.check_mode:
438 self.module.exit_json(changed=True)
439
440 if exists == 0:
441 self.dns_rc = self.create_record()
442 if self.dns_rc != 0:
443 result["msg"] = f"Failed to create DNS record (rc: {int(self.dns_rc)})"
444
445 elif exists == 2:
446 self.dns_rc = self.modify_record()
447 if self.dns_rc != 0:
448 result["msg"] = f"Failed to update DNS record (rc: {int(self.dns_rc)})"
449
450 if self.dns_rc != 0:
451 result["failed"] = True
452 else:
453 result["changed"] = True
454
455 else:
456 result["changed"] = False
457
458 return result
459
460 def create_record(self):
461 update = dns.update.Update(self.zone, keyring=self.keyring, keyname=self.keyname, keyalgorithm=self.algorithm)
462 for entry in self.value:
463 try:
464 update.add(self.module.params["record"], self.module.params["ttl"], self.module.params["type"], entry)
465 except AttributeError:
466 self.module.fail_json(msg="value needed when state=present")
467 except dns.exception.SyntaxError:
468 self.module.fail_json(msg="Invalid/malformed value")
469
470 response = self.__do_update(update)
471 return dns.message.Message.rcode(response)
472
473 def modify_record(self):
474 update = dns.update.Update(self.zone, keyring=self.keyring, keyname=self.keyname, keyalgorithm=self.algorithm)
475
476 if self.module.params["type"].upper() == "NS":
477 # When modifying a NS record, Bind9 silently refuses to delete all the NS entries for a zone:
478 # > 09-May-2022 18:00:50.352 client @0x7fe7dd1f9568 192.168.1.3#45458/key rndc_ddns_ansible:
479 # > updating zone 'lab/IN': attempt to delete all SOA or NS records ignored
480 # https://gitlab.isc.org/isc-projects/bind9/-/blob/v9_18/lib/ns/update.c#L3304
481 # Let's perform dns inserts and updates first, deletes after.
482 query = dns.message.make_query(self.module.params["record"], self.module.params["type"])
483 if self.keyring:
484 query.use_tsig(keyring=self.keyring, keyname=self.keyname, algorithm=self.algorithm)
485
486 try:
487 lookup = self.query(query)
488 except (dns.tsig.PeerBadKey, dns.tsig.PeerBadSignature) as e:
489 self.module.fail_json(msg=f"TSIG update error ({e.__class__.__name__}): {e}")
490 except (OSError, dns.exception.Timeout) as e:
491 self.module.fail_json(msg=f"DNS server error: ({e.__class__.__name__}): {e}")
492
493 lookup_result = lookup.answer[0] if lookup.answer else lookup.authority[0]
494 entries_to_remove = [n.to_text() for n in lookup_result.items if n.to_text() not in self.value]
495 else:
496 update.delete(self.module.params["record"], self.module.params["type"])
497
498 for entry in self.value:
499 try:
500 update.add(self.module.params["record"], self.module.params["ttl"], self.module.params["type"], entry)
501 except AttributeError:
502 self.module.fail_json(msg="value needed when state=present")
503 except dns.exception.SyntaxError:
504 self.module.fail_json(msg="Invalid/malformed value")
505
506 if self.module.params["type"].upper() == "NS":
507 for entry in entries_to_remove:
508 update.delete(self.module.params["record"], self.module.params["type"], entry)
509
510 response = self.__do_update(update)
511
512 return dns.message.Message.rcode(response)
513
514 def remove_record(self):
515 result = {"changed": False, "failed": False}
516
517 if self.record_exists() == 0:
518 return result
519
520 # Check mode and record exists, declared fake change.
521 if self.module.check_mode:
522 self.module.exit_json(changed=True)
523
524 update = dns.update.Update(self.zone, keyring=self.keyring, keyname=self.keyname, keyalgorithm=self.algorithm)
525 update.delete(self.module.params["record"], self.module.params["type"])
526
527 response = self.__do_update(update)
528 self.dns_rc = dns.message.Message.rcode(response)
529
530 if self.dns_rc != 0:
531 result["failed"] = True
532 result["msg"] = f"Failed to delete record (rc: {int(self.dns_rc)})"
533 else:
534 result["changed"] = True
535
536 return result
537
538 def record_exists(self):
539 update = dns.update.Update(self.zone, keyring=self.keyring, keyname=self.keyname, keyalgorithm=self.algorithm)
540 try:
541 update.present(self.module.params["record"], self.module.params["type"])
542 except dns.rdatatype.UnknownRdatatype as e:
543 self.module.fail_json(msg=f"Record error: {e}")
544
545 response = self.__do_update(update)
546 self.dns_rc = dns.message.Message.rcode(response)
547 if self.dns_rc == 0:
548 if self.module.params["state"] == "absent":
549 return 1
550 for entry in self.value:
551 try:
552 update.present(self.module.params["record"], self.module.params["type"], entry)
553 except AttributeError:
554 self.module.fail_json(msg="value needed when state=present")
555 except dns.exception.SyntaxError:
556 self.module.fail_json(msg="Invalid/malformed value")
557 response = self.__do_update(update)
558 self.dns_rc = dns.message.Message.rcode(response)
559 if self.dns_rc == 0:
560 if self.ttl_changed():
561 return 2
562 else:
563 return 1
564 else:
565 return 2
566 else:
567 return 0
568
569 def ttl_changed(self):
570 query = dns.message.make_query(self.fqdn, self.module.params["type"])
571 if self.keyring:
572 query.use_tsig(keyring=self.keyring, keyname=self.keyname, algorithm=self.algorithm)
573
574 try:
575 lookup = self.query(query)
576 except (dns.tsig.PeerBadKey, dns.tsig.PeerBadSignature) as e:
577 self.module.fail_json(msg=f"TSIG update error ({e.__class__.__name__}): {e}")
578 except (OSError, dns.exception.Timeout) as e:
579 self.module.fail_json(msg=f"DNS server error: ({e.__class__.__name__}): {e}")
580
581 if lookup.rcode() != dns.rcode.NOERROR:
582 self.module.fail_json(msg="Failed to lookup TTL of existing matching record.")
583
584 current_ttl = lookup.answer[0].ttl if lookup.answer else lookup.authority[0].ttl
585
586 return current_ttl != self.module.params["ttl"]
587
588
589 def main():
590 tsig_algs = [
591 "HMAC-MD5.SIG-ALG.REG.INT",
592 "hmac-md5",
593 "hmac-sha1",
594 "hmac-sha224",
595 "hmac-sha256",
596 "hmac-sha384",
597 "hmac-sha512",
598 "gss-tsig",
599 ]
600
601 module = AnsibleModule(
602 argument_spec=dict(
603 state=dict(default="present", choices=["present", "absent"], type="str"),
604 server=dict(required=True, type="str"),
605 port=dict(default=53, type="int"),
606 key_name=dict(type="str"),
607 key_secret=dict(type="str", no_log=True),
608 key_algorithm=dict(default="hmac-md5", choices=tsig_algs, type="str"),
609 zone=dict(type="str"),
610 record=dict(required=True, type="str"),
611 type=dict(default="A", type="str"),
612 ttl=dict(default=3600, type="int"),
613 value=dict(type="list", elements="str"),
614 protocol=dict(default="tcp", choices=["tcp", "udp"], type="str"),
615 timeout=dict(default=10, type="float"),
616 ),
617 supports_check_mode=True,
618 )
619
620 deps.validate(module, "dnspython")
621
622 if len(module.params["record"]) == 0:
623 module.fail_json(msg="record cannot be empty.")
624
625 record = RecordManager(module)
626 result = {}
627 if module.params["state"] == "absent":
628 result = record.remove_record()
629 elif module.params["state"] == "present":
630 result = record.create_or_update_record()
631
632 result["dns_rc"] = record.dns_rc
633 result["dns_rc_str"] = dns.rcode.to_text(record.dns_rc)
634 if result["failed"]:
635 module.fail_json(**result)
636 else:
637 result["record"] = dict(
638 zone=record.zone,
639 record=module.params["record"],
640 type=module.params["type"],
641 ttl=module.params["ttl"],
642 value=record.value,
643 )
644
645 module.exit_json(**result)
646
647
648 if __name__ == "__main__":
649 main()