4 # update our DNS names using TSIG-GSS
6 # Copyright (C) Andrew Tridgell 2010
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
28 # ensure we get messages out immediately, so they get in the samba logs,
29 # and don't get swallowed by a timeout
30 os.environ['PYTHONUNBUFFERED'] = '1'
32 # forcing GMT avoids a problem in some timezones with kerberos. Both MIT
33 # heimdal can get mutual authentication errors due to the 24 second difference
34 # between UTC and GMT when using some zone files (eg. the PDT zone from
36 os.environ["TZ"] = "GMT"
38 # Find right directory when running from source tree
39 sys.path.insert(0, "bin/python")
43 from samba import getopt as options
44 from ldb import SCOPE_BASE
45 from samba import dsdb
46 from samba.auth import system_session
47 from samba.samdb import SamDB
48 from samba.dcerpc import netlogon, winbind
50 samba.ensure_third_party_module("dns", "dnspython")
58 parser = optparse.OptionParser("samba_dnsupdate")
59 sambaopts = options.SambaOptions(parser)
60 parser.add_option_group(sambaopts)
61 parser.add_option_group(options.VersionOptions(parser))
62 parser.add_option("--verbose", action="store_true")
63 parser.add_option("--all-names", action="store_true")
64 parser.add_option("--all-interfaces", action="store_true")
65 parser.add_option("--use-file", type="string", help="Use a file, rather than real DNS calls")
66 parser.add_option("--update-list", type="string", help="Add DNS names from the given file")
67 parser.add_option("--update-cache", type="string", help="Cache database of already registered records")
68 parser.add_option("--fail-immediately", action='store_true', help="Exit on first failure")
69 parser.add_option("--no-credentials", dest='nocreds', action='store_true', help="don't try and get credentials")
70 parser.add_option("--no-substitutions", dest='nosubs', action='store_true', help="don't try and expands variables in file specified by --update-list")
75 opts, args = parser.parse_args()
81 lp = sambaopts.get_loadparm()
83 domain = lp.get("realm")
84 host = lp.get("netbios name")
85 if opts.all_interfaces:
88 all_interfaces = False
90 IPs = samba.interface_ips(lp, all_interfaces)
91 nsupdate_cmd = lp.get('nsupdate command')
94 print "No IP interfaces - skipping DNS updates"
100 if i.find(':') != -1:
107 print "IPs: %s" % IPs
110 def get_credentials(lp):
111 """# get credentials if we haven't got them already."""
112 from samba import credentials
114 creds = credentials.Credentials()
116 creds.set_machine_account(lp)
117 creds.set_krb_forwardable(credentials.NO_KRB_FORWARDABLE)
118 (tmp_fd, ccachename) = tempfile.mkstemp()
120 creds.get_named_ccache(lp, ccachename)
121 except RuntimeError as e:
122 os.unlink(ccachename)
126 class dnsobj(object):
127 """an object to hold a parsed DNS line"""
129 def __init__(self, string_form):
130 list = string_form.split()
132 raise Exception("Invalid DNS entry %r" % string_form)
136 self.existing_port = None
137 self.existing_weight = None
140 self.nameservers = []
141 if self.type == 'SRV':
143 raise Exception("Invalid DNS entry %r" % string_form)
146 elif self.type in ['A', 'AAAA']:
147 self.ip = list[2] # usually $IP, which gets replaced
148 elif self.type == 'CNAME':
150 elif self.type == 'NS':
153 raise Exception("Received unexpected DNS reply of type %s: %s" % (self.type, string_form))
157 return "%s %s %s" % (self.type, self.name, self.ip)
158 if self.type == "AAAA":
159 return "%s %s %s" % (self.type, self.name, self.ip)
160 if self.type == "SRV":
161 return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
162 if self.type == "CNAME":
163 return "%s %s %s" % (self.type, self.name, self.dest)
164 if self.type == "NS":
165 return "%s %s %s" % (self.type, self.name, self.dest)
168 def parse_dns_line(line, sub_vars):
169 """parse a DNS line from."""
170 if line.startswith("SRV _ldap._tcp.pdc._msdcs.") and not samdb.am_pdc():
171 # We keep this as compat to the dns_update_list of 4.0/4.1
173 print "Skipping PDC entry (%s) as we are not a PDC" % line
175 subline = samba.substitute_var(line, sub_vars)
176 if subline == '' or subline[0] == "#":
178 return dnsobj(subline)
181 def hostname_match(h1, h2):
182 """see if two hostnames match."""
185 return h1.lower().rstrip('.') == h2.lower().rstrip('.')
188 def check_dns_name(d):
189 """check that a DNS entry exists."""
190 normalised_name = d.name.rstrip('.') + '.'
192 print "Looking for DNS entry %s as %s" % (d, normalised_name)
194 if opts.use_file is not None:
196 dns_file = open(opts.use_file, "r")
200 for line in dns_file:
202 if line == '' or line[0] == "#":
204 if line.lower() == str(d).lower():
208 resolv_conf = os.getenv('RESOLV_WRAPPER_CONF')
210 resolv_conf = '/etc/resolv.conf'
211 resolver = dns.resolver.Resolver(filename=resolv_conf, configure=True)
213 if d.nameservers != []:
214 resolver.nameservers = d.nameservers
216 d.nameservers = resolver.nameservers
219 ans = resolver.query(normalised_name, d.type)
220 except dns.exception.DNSException:
222 print "Failed to find DNS entry %s" % d
224 if d.type in ['A', 'AAAA']:
225 # we need to be sure that our IP is there
227 if str(rdata) == str(d.ip):
229 elif d.type == 'CNAME':
230 for i in range(len(ans)):
231 if hostname_match(ans[i].target, d.dest):
234 for i in range(len(ans)):
235 if hostname_match(ans[i].target, d.dest):
237 elif d.type == 'SRV':
240 print "Checking %s against %s" % (rdata, d)
241 if hostname_match(rdata.target, d.dest):
242 if str(rdata.port) == str(d.port):
245 d.existing_port = str(rdata.port)
246 d.existing_weight = str(rdata.weight)
249 print "Failed to find matching DNS entry %s" % d
254 def get_subst_vars(samdb):
255 """get the list of substitution vars."""
259 vars['DNSDOMAIN'] = samdb.domain_dns_name()
260 vars['DNSFOREST'] = samdb.forest_dns_name()
261 vars['HOSTNAME'] = samdb.host_dns_name()
262 vars['NTDSGUID'] = samdb.get_ntds_GUID()
263 vars['SITE'] = samdb.server_site_name()
264 res = samdb.search(base=samdb.get_default_basedn(), scope=SCOPE_BASE, attrs=["objectGUID"])
265 guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
266 vars['DOMAINGUID'] = guid
269 vars['IF_RWDC'] = "# "
270 vars['IF_RODC'] = "# "
271 vars['IF_PDC'] = "# "
273 vars['IF_RWGC'] = "# "
274 vars['IF_ROGC'] = "# "
275 vars['IF_DNS_DOMAIN'] = "# "
276 vars['IF_RWDNS_DOMAIN'] = "# "
277 vars['IF_RODNS_DOMAIN'] = "# "
278 vars['IF_DNS_FOREST'] = "# "
279 vars['IF_RWDNS_FOREST'] = "# "
280 vars['IF_R0DNS_FOREST'] = "# "
282 am_rodc = samdb.am_rodc()
291 # check if we "are DNS server"
292 res = samdb.search(base=samdb.get_config_basedn(),
293 expression='(objectguid=%s)' % vars['NTDSGUID'],
294 attrs=["options", "msDS-hasMasterNCs"])
297 if "options" in res[0]:
298 options = int(res[0]["options"][0])
299 if (options & dsdb.DS_NTDSDSA_OPT_IS_GC) != 0:
306 basedn = str(samdb.get_default_basedn())
307 forestdn = str(samdb.get_root_basedn())
309 if "msDS-hasMasterNCs" in res[0]:
310 for e in res[0]["msDS-hasMasterNCs"]:
311 if str(e) == "DC=DomainDnsZones,%s" % basedn:
312 vars['IF_DNS_DOMAIN'] = ""
314 vars['IF_RODNS_DOMAIN'] = ""
316 vars['IF_RWDNS_DOMAIN'] = ""
317 if str(e) == "DC=ForestDnsZones,%s" % forestdn:
318 vars['IF_DNS_FOREST'] = ""
320 vars['IF_RODNS_FOREST'] = ""
322 vars['IF_RWDNS_FOREST'] = ""
327 def call_nsupdate(d, op="add"):
328 """call nsupdate for an entry."""
329 global ccachename, nsupdate_cmd, krb5conf
331 assert(op in ["add", "delete"])
334 print "Calling nsupdate for %s (%s)" % (d, op)
336 if opts.use_file is not None:
338 rfile = open(opts.use_file, 'r+')
341 rfile = open(opts.use_file, 'w+')
342 # Open it for reading again, in case someone else got to it first
343 rfile = open(opts.use_file, 'r+')
344 fcntl.lockf(rfile, fcntl.LOCK_EX)
345 (file_dir, file_name) = os.path.split(opts.use_file)
346 (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
347 wfile = os.fdopen(tmp_fd, 'a')
351 l = parse_dns_line(line, {})
352 if str(l).lower() == str(d).lower():
356 wfile.write(str(d)+"\n")
357 os.rename(tmpfile, opts.use_file)
358 fcntl.lockf(rfile, fcntl.LOCK_UN)
361 normalised_name = d.name.rstrip('.') + '.'
363 (tmp_fd, tmpfile) = tempfile.mkstemp()
364 f = os.fdopen(tmp_fd, 'w')
365 if d.nameservers != []:
366 f.write('server %s\n' % d.nameservers[0])
368 f.write("update %s %s %u A %s\n" % (op, normalised_name, default_ttl, d.ip))
370 f.write("update %s %s %u AAAA %s\n" % (op, normalised_name, default_ttl, d.ip))
372 if op == "add" and d.existing_port is not None:
373 f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
374 d.existing_port, d.dest))
375 f.write("update %s %s %u SRV 0 100 %s %s\n" % (op, normalised_name, default_ttl, d.port, d.dest))
376 if d.type == "CNAME":
377 f.write("update %s %s %u CNAME %s\n" % (op, normalised_name, default_ttl, d.dest))
379 f.write("update %s %s %u NS %s\n" % (op, normalised_name, default_ttl, d.dest))
387 os.environ["KRB5CCNAME"] = ccachename
389 cmd = nsupdate_cmd[:]
393 env["KRB5_CONFIG"] = krb5conf
395 env["KRB5CCNAME"] = ccachename
396 ret = subprocess.call(cmd, shell=False, env=env)
398 if opts.fail_immediately:
400 print("Failed update with %s" % tmpfile)
402 error_count = error_count + 1
404 print("Failed nsupdate: %d" % ret)
405 except Exception, estr:
406 if opts.fail_immediately:
408 error_count = error_count + 1
410 print("Failed nsupdate: %s : %s" % (str(d), estr))
415 def rodc_dns_update(d, t, op):
416 '''a single DNS update via the RODC netlogon call'''
419 assert(op in ["add", "delete"])
422 print "Calling netlogon RODC update for %s" % d
425 netlogon.NlDnsLdapAtSite : netlogon.NlDnsInfoTypeNone,
426 netlogon.NlDnsGcAtSite : netlogon.NlDnsDomainNameAlias,
427 netlogon.NlDnsDsaCname : netlogon.NlDnsDomainNameAlias,
428 netlogon.NlDnsKdcAtSite : netlogon.NlDnsInfoTypeNone,
429 netlogon.NlDnsDcAtSite : netlogon.NlDnsInfoTypeNone,
430 netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
431 netlogon.NlDnsGenericGcAtSite : netlogon.NlDnsDomainNameAlias
434 w = winbind.winbind("irpc:winbind_server", lp)
435 dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
437 name = netlogon.NL_DNS_NAME_INFO()
439 name.dns_domain_info_type = typemap[t]
442 if d.port is not None:
443 name.port = int(d.port)
445 name.dns_register = True
447 name.dns_register = False
448 dns_names.names = [ name ]
449 site_name = sub_vars['SITE'].decode('utf-8')
454 ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
455 if ret_names.names[0].status != 0:
456 print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
457 error_count = error_count + 1
458 except RuntimeError, reason:
459 print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
460 error_count = error_count + 1
462 if error_count != 0 and opts.fail_immediately:
466 def call_rodc_update(d, op="add"):
467 '''RODCs need to use the netlogon API for nsupdate'''
470 assert(op in ["add", "delete"])
472 # we expect failure for 3268 if we aren't a GC
473 if d.port is not None and int(d.port) == 3268:
476 # map the DNS request to a netlogon update type
478 netlogon.NlDnsLdapAtSite : '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
479 netlogon.NlDnsGcAtSite : '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
480 netlogon.NlDnsDsaCname : '${NTDSGUID}._msdcs.${DNSFOREST}',
481 netlogon.NlDnsKdcAtSite : '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
482 netlogon.NlDnsDcAtSite : '_ldap._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
483 netlogon.NlDnsRfc1510KdcAtSite : '_kerberos._tcp.${SITE}._sites.${DNSDOMAIN}',
484 netlogon.NlDnsGenericGcAtSite : '_gc._tcp.${SITE}._sites.${DNSFOREST}'
488 subname = samba.substitute_var(map[t], sub_vars)
489 if subname.lower() == d.name.lower():
490 # found a match - do the update
491 rodc_dns_update(d, t, op)
494 print("Unable to map to netlogon DNS update: %s" % d)
497 # get the list of DNS entries we should have
499 dns_update_list = opts.update_list
501 dns_update_list = lp.private_path('dns_update_list')
503 if opts.update_cache:
504 dns_update_cache = opts.update_cache
506 dns_update_cache = lp.private_path('dns_update_cache')
508 # use our private krb5.conf to avoid problems with the wrong domain
509 # bind9 nsupdate wants the default domain set
510 krb5conf = lp.private_path('krb5.conf')
511 os.environ['KRB5_CONFIG'] = krb5conf
513 file = open(dns_update_list, "r")
518 samdb = SamDB(url=lp.samdb_url(), session_info=system_session(), lp=lp)
520 # get the substitution dictionary
521 sub_vars = get_subst_vars(samdb)
523 # build up a list of update commands to pass to nsupdate
532 rebuild_cache = False
534 cfile = open(dns_update_cache, 'r+')
537 cfile = open(dns_update_cache, 'w+')
538 # Open it for reading again, in case someone else got to it first
539 cfile = open(dns_update_cache, 'r+')
540 fcntl.lockf(cfile, fcntl.LOCK_EX)
543 if line == '' or line[0] == "#":
545 c = parse_dns_line(line, {})
548 if str(c) not in cache_set:
550 cache_set.add(str(c))
552 # read each line, and check that the DNS name exists
555 if line == '' or line[0] == "#":
557 d = parse_dns_line(line, sub_vars)
560 if d.type == 'A' and len(IP4s) == 0:
562 if d.type == 'AAAA' and len(IP6s) == 0:
564 if str(d) not in dup_set:
568 # now expand the entries, if any are A record with ip set to $IP
569 # then replace with multiple entries, one for each interface IP
575 for i in range(len(IP4s)-1):
581 for i in range(len(IP6s)-1):
586 # now check if the entries already exist on the DNS server
590 if str(c).lower() == str(d).lower():
596 update_list.append(d)
598 print "force update: %s" % d
599 elif not check_dns_name(d):
600 update_list.append(d)
602 print "need update: %s" % d
608 if str(c).lower() == str(d).lower():
614 if not opts.all_names and not check_dns_name(c):
616 delete_list.append(c)
618 print "need delete: %s" % c
620 if len(delete_list) == 0 and len(update_list) == 0 and not rebuild_cache:
622 print "No DNS updates needed"
626 print "%d DNS updates and %d DNS deletes needed" % (len(update_list), len(delete_list))
629 if len(delete_list) != 0 or len(update_list) != 0:
633 # ask nsupdate to delete entries as needed
634 for d in delete_list:
636 if d.name.lower() == domain.lower():
638 print "skip delete (rodc): %s" % d
640 if not d.type in [ 'A', 'AAAA' ]:
642 print "delete (rodc): %s" % d
643 call_rodc_update(d, op="delete")
646 print "delete (nsupdate): %s" % d
647 call_nsupdate(d, op="delete")
650 print "delete (nsupdate): %s" % d
651 call_nsupdate(d, op="delete")
653 # ask nsupdate to add entries as needed
654 for d in update_list:
656 if d.name.lower() == domain.lower():
658 print "skip (rodc): %s" % d
660 if not d.type in [ 'A', 'AAAA' ]:
662 print "update (rodc): %s" % d
666 print "update (nsupdate): %s" % d
670 print "update(nsupdate): %s" % d
674 (file_dir, file_name) = os.path.split(dns_update_cache)
675 (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
676 wfile = os.fdopen(tmp_fd, 'a')
678 wfile.write(str(d)+"\n")
679 os.rename(tmpfile, dns_update_cache)
680 fcntl.lockf(cfile, fcntl.LOCK_UN)
682 # delete the ccache if we created it
683 if ccachename is not None:
684 os.unlink(ccachename)
687 print("Failed update of %u entries" % error_count)
688 sys.exit(error_count)