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-substiutions", 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
113 global ccachename, creds
114 if creds is not None:
116 creds = credentials.Credentials()
118 creds.set_machine_account(lp)
119 creds.set_krb_forwardable(credentials.NO_KRB_FORWARDABLE)
120 (tmp_fd, ccachename) = tempfile.mkstemp()
122 creds.get_named_ccache(lp, ccachename)
123 except RuntimeError as e:
124 os.unlink(ccachename)
128 class dnsobj(object):
129 """an object to hold a parsed DNS line"""
131 def __init__(self, string_form):
132 list = string_form.split()
134 raise Exception("Invalid DNS entry %r" % string_form)
138 self.existing_port = None
139 self.existing_weight = None
142 self.nameservers = []
143 if self.type == 'SRV':
145 raise Exception("Invalid DNS entry %r" % string_form)
148 elif self.type in ['A', 'AAAA']:
149 self.ip = list[2] # usually $IP, which gets replaced
150 elif self.type == 'CNAME':
152 elif self.type == 'NS':
155 raise Exception("Received unexpected DNS reply of type %s: %s" % (self.type, string_form))
159 return "%s %s %s" % (self.type, self.name, self.ip)
160 if self.type == "AAAA":
161 return "%s %s %s" % (self.type, self.name, self.ip)
162 if self.type == "SRV":
163 return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
164 if self.type == "CNAME":
165 return "%s %s %s" % (self.type, self.name, self.dest)
166 if self.type == "NS":
167 return "%s %s %s" % (self.type, self.name, self.dest)
170 def parse_dns_line(line, sub_vars):
171 """parse a DNS line from."""
172 if line.startswith("SRV _ldap._tcp.pdc._msdcs.") and not samdb.am_pdc():
173 # We keep this as compat to the dns_update_list of 4.0/4.1
175 print "Skipping PDC entry (%s) as we are not a PDC" % line
177 subline = samba.substitute_var(line, sub_vars)
178 if subline == '' or subline[0] == "#":
180 return dnsobj(subline)
183 def hostname_match(h1, h2):
184 """see if two hostnames match."""
187 return h1.lower().rstrip('.') == h2.lower().rstrip('.')
190 def check_dns_name(d):
191 """check that a DNS entry exists."""
192 normalised_name = d.name.rstrip('.') + '.'
194 print "Looking for DNS entry %s as %s" % (d, normalised_name)
196 if opts.use_file is not None:
198 dns_file = open(opts.use_file, "r")
202 for line in dns_file:
204 if line == '' or line[0] == "#":
206 if line.lower() == str(d).lower():
210 resolver = dns.resolver.Resolver()
212 if d.nameservers != []:
213 resolver.nameservers = d.nameservers
215 d.nameservers = resolver.nameservers
218 ans = resolver.query(normalised_name, d.type)
219 except dns.exception.DNSException:
221 print "Failed to find DNS entry %s" % d
223 if d.type in ['A', 'AAAA']:
224 # we need to be sure that our IP is there
226 if str(rdata) == str(d.ip):
228 elif d.type == 'CNAME':
229 for i in range(len(ans)):
230 if hostname_match(ans[i].target, d.dest):
233 for i in range(len(ans)):
234 if hostname_match(ans[i].target, d.dest):
236 elif d.type == 'SRV':
239 print "Checking %s against %s" % (rdata, d)
240 if hostname_match(rdata.target, d.dest):
241 if str(rdata.port) == str(d.port):
244 d.existing_port = str(rdata.port)
245 d.existing_weight = str(rdata.weight)
248 print "Failed to find matching DNS entry %s" % d
253 def get_subst_vars(samdb):
254 """get the list of substitution vars."""
258 vars['DNSDOMAIN'] = samdb.domain_dns_name()
259 vars['DNSFOREST'] = samdb.forest_dns_name()
260 vars['HOSTNAME'] = samdb.host_dns_name()
261 vars['NTDSGUID'] = samdb.get_ntds_GUID()
262 vars['SITE'] = samdb.server_site_name()
263 res = samdb.search(base=samdb.get_default_basedn(), scope=SCOPE_BASE, attrs=["objectGUID"])
264 guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
265 vars['DOMAINGUID'] = guid
268 vars['IF_RWDC'] = "# "
269 vars['IF_RODC'] = "# "
270 vars['IF_PDC'] = "# "
272 vars['IF_RWGC'] = "# "
273 vars['IF_ROGC'] = "# "
274 vars['IF_DNS_DOMAIN'] = "# "
275 vars['IF_RWDNS_DOMAIN'] = "# "
276 vars['IF_RODNS_DOMAIN'] = "# "
277 vars['IF_DNS_FOREST'] = "# "
278 vars['IF_RWDNS_FOREST'] = "# "
279 vars['IF_R0DNS_FOREST'] = "# "
281 am_rodc = samdb.am_rodc()
290 # check if we "are DNS server"
291 res = samdb.search(base=samdb.get_config_basedn(),
292 expression='(objectguid=%s)' % vars['NTDSGUID'],
293 attrs=["options", "msDS-hasMasterNCs"])
296 if "options" in res[0]:
297 options = int(res[0]["options"][0])
298 if (options & dsdb.DS_NTDSDSA_OPT_IS_GC) != 0:
305 basedn = str(samdb.get_default_basedn())
306 forestdn = str(samdb.get_root_basedn())
308 if "msDS-hasMasterNCs" in res[0]:
309 for e in res[0]["msDS-hasMasterNCs"]:
310 if str(e) == "DC=DomainDnsZones,%s" % basedn:
311 vars['IF_DNS_DOMAIN'] = ""
313 vars['IF_RODNS_DOMAIN'] = ""
315 vars['IF_RWDNS_DOMAIN'] = ""
316 if str(e) == "DC=ForestDnsZones,%s" % forestdn:
317 vars['IF_DNS_FOREST'] = ""
319 vars['IF_RODNS_FOREST'] = ""
321 vars['IF_RWDNS_FOREST'] = ""
326 def call_nsupdate(d, op="add"):
327 """call nsupdate for an entry."""
328 global ccachename, nsupdate_cmd, krb5conf
330 assert(op in ["add", "delete"])
333 print "Calling nsupdate for %s (%s)" % (d, op)
335 if opts.use_file is not None:
337 rfile = open(opts.use_file, 'r+')
340 rfile = open(opts.use_file, 'w+')
341 # Open it for reading again, in case someone else got to it first
342 rfile = open(opts.use_file, 'r+')
343 fcntl.lockf(rfile, fcntl.LOCK_EX)
344 (file_dir, file_name) = os.path.split(opts.use_file)
345 (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
346 wfile = os.fdopen(tmp_fd, 'a')
350 l = parse_dns_line(line, {})
351 if str(l).lower() == str(d).lower():
355 wfile.write(str(d)+"\n")
356 os.rename(tmpfile, opts.use_file)
357 fcntl.lockf(rfile, fcntl.LOCK_UN)
360 normalised_name = d.name.rstrip('.') + '.'
362 (tmp_fd, tmpfile) = tempfile.mkstemp()
363 f = os.fdopen(tmp_fd, 'w')
364 if d.nameservers != []:
365 f.write('server %s\n' % d.nameservers[0])
367 f.write("update %s %s %u A %s\n" % (op, normalised_name, default_ttl, d.ip))
369 f.write("update %s %s %u AAAA %s\n" % (op, normalised_name, default_ttl, d.ip))
371 if op == "add" and d.existing_port is not None:
372 f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
373 d.existing_port, d.dest))
374 f.write("update %s %s %u SRV 0 100 %s %s\n" % (op, normalised_name, default_ttl, d.port, d.dest))
375 if d.type == "CNAME":
376 f.write("update %s %s %u CNAME %s\n" % (op, normalised_name, default_ttl, d.dest))
378 f.write("update %s %s %u NS %s\n" % (op, normalised_name, default_ttl, d.dest))
386 os.environ["KRB5CCNAME"] = ccachename
388 cmd = nsupdate_cmd[:]
392 env["KRB5_CONFIG"] = krb5conf
394 env["KRB5CCNAME"] = ccachename
395 ret = subprocess.call(cmd, shell=False, env=env)
397 if opts.fail_immediately:
399 print("Failed update with %s" % tmpfile)
401 error_count = error_count + 1
403 print("Failed nsupdate: %d" % ret)
404 except Exception, estr:
405 if opts.fail_immediately:
407 error_count = error_count + 1
409 print("Failed nsupdate: %s : %s" % (str(d), estr))
414 def rodc_dns_update(d, t, op):
415 '''a single DNS update via the RODC netlogon call'''
418 assert(op in ["add", "delete"])
421 print "Calling netlogon RODC update for %s" % d
424 netlogon.NlDnsLdapAtSite : netlogon.NlDnsInfoTypeNone,
425 netlogon.NlDnsGcAtSite : netlogon.NlDnsDomainNameAlias,
426 netlogon.NlDnsDsaCname : netlogon.NlDnsDomainNameAlias,
427 netlogon.NlDnsKdcAtSite : netlogon.NlDnsInfoTypeNone,
428 netlogon.NlDnsDcAtSite : netlogon.NlDnsInfoTypeNone,
429 netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
430 netlogon.NlDnsGenericGcAtSite : netlogon.NlDnsDomainNameAlias
433 w = winbind.winbind("irpc:winbind_server", lp)
434 dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
436 name = netlogon.NL_DNS_NAME_INFO()
438 name.dns_domain_info_type = typemap[t]
441 if d.port is not None:
442 name.port = int(d.port)
444 name.dns_register = True
446 name.dns_register = False
447 dns_names.names = [ name ]
448 site_name = sub_vars['SITE'].decode('utf-8')
453 ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
454 if ret_names.names[0].status != 0:
455 print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
456 error_count = error_count + 1
457 except RuntimeError, reason:
458 print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
459 error_count = error_count + 1
461 if error_count != 0 and opts.fail_immediately:
465 def call_rodc_update(d, op="add"):
466 '''RODCs need to use the netlogon API for nsupdate'''
469 assert(op in ["add", "delete"])
471 # we expect failure for 3268 if we aren't a GC
472 if d.port is not None and int(d.port) == 3268:
475 # map the DNS request to a netlogon update type
477 netlogon.NlDnsLdapAtSite : '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
478 netlogon.NlDnsGcAtSite : '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
479 netlogon.NlDnsDsaCname : '${NTDSGUID}._msdcs.${DNSFOREST}',
480 netlogon.NlDnsKdcAtSite : '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
481 netlogon.NlDnsDcAtSite : '_ldap._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
482 netlogon.NlDnsRfc1510KdcAtSite : '_kerberos._tcp.${SITE}._sites.${DNSDOMAIN}',
483 netlogon.NlDnsGenericGcAtSite : '_gc._tcp.${SITE}._sites.${DNSFOREST}'
487 subname = samba.substitute_var(map[t], sub_vars)
488 if subname.lower() == d.name.lower():
489 # found a match - do the update
490 rodc_dns_update(d, t, op)
493 print("Unable to map to netlogon DNS update: %s" % d)
496 # get the list of DNS entries we should have
498 dns_update_list = opts.update_list
500 dns_update_list = lp.private_path('dns_update_list')
502 if opts.update_cache:
503 dns_update_cache = opts.update_cache
505 dns_update_cache = lp.private_path('dns_update_cache')
507 # use our private krb5.conf to avoid problems with the wrong domain
508 # bind9 nsupdate wants the default domain set
509 krb5conf = lp.private_path('krb5.conf')
510 os.environ['KRB5_CONFIG'] = krb5conf
512 file = open(dns_update_list, "r")
517 samdb = SamDB(url=lp.samdb_url(), session_info=system_session(), lp=lp)
519 # get the substitution dictionary
520 sub_vars = get_subst_vars(samdb)
522 # build up a list of update commands to pass to nsupdate
531 rebuild_cache = False
533 cfile = open(dns_update_cache, 'r+')
536 cfile = open(dns_update_cache, 'w+')
537 # Open it for reading again, in case someone else got to it first
538 cfile = open(dns_update_cache, 'r+')
539 fcntl.lockf(cfile, fcntl.LOCK_EX)
542 if line == '' or line[0] == "#":
544 c = parse_dns_line(line, {})
547 if str(c) not in cache_set:
549 cache_set.add(str(c))
551 # read each line, and check that the DNS name exists
554 if line == '' or line[0] == "#":
556 d = parse_dns_line(line, sub_vars)
559 if d.type == 'A' and len(IP4s) == 0:
561 if d.type == 'AAAA' and len(IP6s) == 0:
563 if str(d) not in dup_set:
567 # now expand the entries, if any are A record with ip set to $IP
568 # then replace with multiple entries, one for each interface IP
574 for i in range(len(IP4s)-1):
580 for i in range(len(IP6s)-1):
585 # now check if the entries already exist on the DNS server
589 if str(c).lower() == str(d).lower():
594 if opts.all_names or not check_dns_name(d):
595 update_list.append(d)
600 if str(c).lower() == str(d).lower():
606 if not opts.all_names and not check_dns_name(c):
608 delete_list.append(c)
610 if len(delete_list) == 0 and len(update_list) == 0 and not rebuild_cache:
612 print "No DNS updates needed"
616 if len(delete_list) != 0 or len(update_list) != 0:
620 # ask nsupdate to delete entries as needed
621 for d in delete_list:
623 if d.name.lower() == domain.lower():
625 if not d.type in [ 'A', 'AAAA' ]:
626 call_rodc_update(d, op="delete")
628 call_nsupdate(d, op="delete")
630 call_nsupdate(d, op="delete")
632 # ask nsupdate to add entries as needed
633 for d in update_list:
635 if d.name.lower() == domain.lower():
637 if not d.type in [ 'A', 'AAAA' ]:
645 (file_dir, file_name) = os.path.split(dns_update_cache)
646 (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
647 wfile = os.fdopen(tmp_fd, 'a')
649 wfile.write(str(d)+"\n")
650 os.rename(tmpfile, dns_update_cache)
651 fcntl.lockf(cfile, fcntl.LOCK_UN)
653 # delete the ccache if we created it
654 if ccachename is not None:
655 os.unlink(ccachename)
658 print("Failed update of %u entries" % error_count)
659 sys.exit(error_count)