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 if self.type == 'SRV':
144 raise Exception("Invalid DNS entry %r" % string_form)
147 elif self.type in ['A', 'AAAA']:
148 self.ip = list[2] # usually $IP, which gets replaced
149 elif self.type == 'CNAME':
151 elif self.type == 'NS':
154 raise Exception("Received unexpected DNS reply of type %s: %s" % (self.type, string_form))
158 return "%s %s %s" % (self.type, self.name, self.ip)
159 if self.type == "AAAA":
160 return "%s %s %s" % (self.type, self.name, self.ip)
161 if self.type == "SRV":
162 return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
163 if self.type == "CNAME":
164 return "%s %s %s" % (self.type, self.name, self.dest)
165 if self.type == "NS":
166 return "%s %s %s" % (self.type, self.name, self.dest)
169 def parse_dns_line(line, sub_vars):
170 """parse a DNS line from."""
171 if line.startswith("SRV _ldap._tcp.pdc._msdcs.") and not samdb.am_pdc():
172 # We keep this as compat to the dns_update_list of 4.0/4.1
174 print "Skipping PDC entry (%s) as we are not a PDC" % line
176 subline = samba.substitute_var(line, sub_vars)
177 if subline == '' or subline[0] == "#":
179 return dnsobj(subline)
182 def hostname_match(h1, h2):
183 """see if two hostnames match."""
186 return h1.lower().rstrip('.') == h2.lower().rstrip('.')
189 def check_dns_name(d):
190 """check that a DNS entry exists."""
191 normalised_name = d.name.rstrip('.') + '.'
193 print "Looking for DNS entry %s as %s" % (d, normalised_name)
195 if opts.use_file is not None:
197 dns_file = open(opts.use_file, "r")
201 for line in dns_file:
203 if line == '' or line[0] == "#":
205 if line.lower() == str(d).lower():
209 resolver = dns.resolver.Resolver()
212 if getattr(d, 'nameservers', None):
213 resolver.nameservers = list(d.nameservers)
214 ans = resolver.query(normalised_name, d.type)
215 except dns.exception.DNSException:
217 print "Failed to find DNS entry %s" % d
219 if d.type in ['A', 'AAAA']:
220 # we need to be sure that our IP is there
222 if str(rdata) == str(d.ip):
224 elif d.type == 'CNAME':
225 for i in range(len(ans)):
226 if hostname_match(ans[i].target, d.dest):
229 for i in range(len(ans)):
230 if hostname_match(ans[i].target, d.dest):
232 elif d.type == 'SRV':
235 print "Checking %s against %s" % (rdata, d)
236 if hostname_match(rdata.target, d.dest):
237 if str(rdata.port) == str(d.port):
240 d.existing_port = str(rdata.port)
241 d.existing_weight = str(rdata.weight)
244 print "Failed to find matching DNS entry %s" % d
249 def get_subst_vars(samdb):
250 """get the list of substitution vars."""
254 vars['DNSDOMAIN'] = samdb.domain_dns_name()
255 vars['DNSFOREST'] = samdb.forest_dns_name()
256 vars['HOSTNAME'] = samdb.host_dns_name()
257 vars['NTDSGUID'] = samdb.get_ntds_GUID()
258 vars['SITE'] = samdb.server_site_name()
259 res = samdb.search(base=samdb.get_default_basedn(), scope=SCOPE_BASE, attrs=["objectGUID"])
260 guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
261 vars['DOMAINGUID'] = guid
264 vars['IF_RWDC'] = "# "
265 vars['IF_RODC'] = "# "
266 vars['IF_PDC'] = "# "
268 vars['IF_RWGC'] = "# "
269 vars['IF_ROGC'] = "# "
270 vars['IF_DNS_DOMAIN'] = "# "
271 vars['IF_RWDNS_DOMAIN'] = "# "
272 vars['IF_RODNS_DOMAIN'] = "# "
273 vars['IF_DNS_FOREST'] = "# "
274 vars['IF_RWDNS_FOREST'] = "# "
275 vars['IF_R0DNS_FOREST'] = "# "
277 am_rodc = samdb.am_rodc()
286 # check if we "are DNS server"
287 res = samdb.search(base=samdb.get_config_basedn(),
288 expression='(objectguid=%s)' % vars['NTDSGUID'],
289 attrs=["options", "msDS-hasMasterNCs"])
292 if "options" in res[0]:
293 options = int(res[0]["options"][0])
294 if (options & dsdb.DS_NTDSDSA_OPT_IS_GC) != 0:
301 basedn = str(samdb.get_default_basedn())
302 forestdn = str(samdb.get_root_basedn())
304 if "msDS-hasMasterNCs" in res[0]:
305 for e in res[0]["msDS-hasMasterNCs"]:
306 if str(e) == "DC=DomainDnsZones,%s" % basedn:
307 vars['IF_DNS_DOMAIN'] = ""
309 vars['IF_RODNS_DOMAIN'] = ""
311 vars['IF_RWDNS_DOMAIN'] = ""
312 if str(e) == "DC=ForestDnsZones,%s" % forestdn:
313 vars['IF_DNS_FOREST'] = ""
315 vars['IF_RODNS_FOREST'] = ""
317 vars['IF_RWDNS_FOREST'] = ""
322 def call_nsupdate(d, op="add"):
323 """call nsupdate for an entry."""
324 global ccachename, nsupdate_cmd, krb5conf
326 assert(op in ["add", "delete"])
329 print "Calling nsupdate for %s (%s)" % (d, op)
331 if opts.use_file is not None:
333 rfile = open(opts.use_file, 'r+')
336 rfile = open(opts.use_file, 'w+')
337 # Open it for reading again, in case someone else got to it first
338 rfile = open(opts.use_file, 'r+')
339 fcntl.lockf(rfile, fcntl.LOCK_EX)
340 (file_dir, file_name) = os.path.split(opts.use_file)
341 (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
342 wfile = os.fdopen(tmp_fd, 'a')
346 l = parse_dns_line(line, {})
347 if str(l).lower() == str(d).lower():
351 wfile.write(str(d)+"\n")
352 os.rename(tmpfile, opts.use_file)
353 fcntl.lockf(rfile, fcntl.LOCK_UN)
356 normalised_name = d.name.rstrip('.') + '.'
358 (tmp_fd, tmpfile) = tempfile.mkstemp()
359 f = os.fdopen(tmp_fd, 'w')
360 if getattr(d, 'nameservers', None):
361 f.write('server %s\n' % d.nameservers[0])
363 f.write("update %s %s %u A %s\n" % (op, normalised_name, default_ttl, d.ip))
365 f.write("update %s %s %u AAAA %s\n" % (op, normalised_name, default_ttl, d.ip))
367 if op == "add" and d.existing_port is not None:
368 f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
369 d.existing_port, d.dest))
370 f.write("update %s %s %u SRV 0 100 %s %s\n" % (op, normalised_name, default_ttl, d.port, d.dest))
371 if d.type == "CNAME":
372 f.write("update %s %s %u CNAME %s\n" % (op, normalised_name, default_ttl, d.dest))
374 f.write("update %s %s %u NS %s\n" % (op, normalised_name, default_ttl, d.dest))
382 os.environ["KRB5CCNAME"] = ccachename
384 cmd = nsupdate_cmd[:]
388 env["KRB5_CONFIG"] = krb5conf
390 env["KRB5CCNAME"] = ccachename
391 ret = subprocess.call(cmd, shell=False, env=env)
393 if opts.fail_immediately:
395 print("Failed update with %s" % tmpfile)
397 error_count = error_count + 1
399 print("Failed nsupdate: %d" % ret)
400 except Exception, estr:
401 if opts.fail_immediately:
403 error_count = error_count + 1
405 print("Failed nsupdate: %s : %s" % (str(d), estr))
410 def rodc_dns_update(d, t, op):
411 '''a single DNS update via the RODC netlogon call'''
414 assert(op in ["add", "delete"])
417 print "Calling netlogon RODC update for %s" % d
420 netlogon.NlDnsLdapAtSite : netlogon.NlDnsInfoTypeNone,
421 netlogon.NlDnsGcAtSite : netlogon.NlDnsDomainNameAlias,
422 netlogon.NlDnsDsaCname : netlogon.NlDnsDomainNameAlias,
423 netlogon.NlDnsKdcAtSite : netlogon.NlDnsInfoTypeNone,
424 netlogon.NlDnsDcAtSite : netlogon.NlDnsInfoTypeNone,
425 netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
426 netlogon.NlDnsGenericGcAtSite : netlogon.NlDnsDomainNameAlias
429 w = winbind.winbind("irpc:winbind_server", lp)
430 dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
432 name = netlogon.NL_DNS_NAME_INFO()
434 name.dns_domain_info_type = typemap[t]
437 if d.port is not None:
438 name.port = int(d.port)
440 name.dns_register = True
442 name.dns_register = False
443 dns_names.names = [ name ]
444 site_name = sub_vars['SITE'].decode('utf-8')
449 ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
450 if ret_names.names[0].status != 0:
451 print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
452 error_count = error_count + 1
453 except RuntimeError, reason:
454 print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
455 error_count = error_count + 1
457 if error_count != 0 and opts.fail_immediately:
461 def call_rodc_update(d, op="add"):
462 '''RODCs need to use the netlogon API for nsupdate'''
465 assert(op in ["add", "delete"])
467 # we expect failure for 3268 if we aren't a GC
468 if d.port is not None and int(d.port) == 3268:
471 # map the DNS request to a netlogon update type
473 netlogon.NlDnsLdapAtSite : '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
474 netlogon.NlDnsGcAtSite : '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
475 netlogon.NlDnsDsaCname : '${NTDSGUID}._msdcs.${DNSFOREST}',
476 netlogon.NlDnsKdcAtSite : '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
477 netlogon.NlDnsDcAtSite : '_ldap._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
478 netlogon.NlDnsRfc1510KdcAtSite : '_kerberos._tcp.${SITE}._sites.${DNSDOMAIN}',
479 netlogon.NlDnsGenericGcAtSite : '_gc._tcp.${SITE}._sites.${DNSFOREST}'
483 subname = samba.substitute_var(map[t], sub_vars)
484 if subname.lower() == d.name.lower():
485 # found a match - do the update
486 rodc_dns_update(d, t, op)
489 print("Unable to map to netlogon DNS update: %s" % d)
492 # get the list of DNS entries we should have
494 dns_update_list = opts.update_list
496 dns_update_list = lp.private_path('dns_update_list')
498 if opts.update_cache:
499 dns_update_cache = opts.update_cache
501 dns_update_cache = lp.private_path('dns_update_cache')
503 # use our private krb5.conf to avoid problems with the wrong domain
504 # bind9 nsupdate wants the default domain set
505 krb5conf = lp.private_path('krb5.conf')
506 os.environ['KRB5_CONFIG'] = krb5conf
508 file = open(dns_update_list, "r")
513 samdb = SamDB(url=lp.samdb_url(), session_info=system_session(), lp=lp)
515 # get the substitution dictionary
516 sub_vars = get_subst_vars(samdb)
518 # build up a list of update commands to pass to nsupdate
527 rebuild_cache = False
529 cfile = open(dns_update_cache, 'r+')
532 cfile = open(dns_update_cache, 'w+')
533 # Open it for reading again, in case someone else got to it first
534 cfile = open(dns_update_cache, 'r+')
535 fcntl.lockf(cfile, fcntl.LOCK_EX)
538 if line == '' or line[0] == "#":
540 c = parse_dns_line(line, {})
543 if str(c) not in cache_set:
545 cache_set.add(str(c))
547 # read each line, and check that the DNS name exists
550 if line == '' or line[0] == "#":
552 d = parse_dns_line(line, sub_vars)
555 if d.type == 'A' and len(IP4s) == 0:
557 if d.type == 'AAAA' and len(IP6s) == 0:
559 if str(d) not in dup_set:
563 # now expand the entries, if any are A record with ip set to $IP
564 # then replace with multiple entries, one for each interface IP
570 for i in range(len(IP4s)-1):
576 for i in range(len(IP6s)-1):
581 # now check if the entries already exist on the DNS server
585 if str(c).lower() == str(d).lower():
590 if opts.all_names or not check_dns_name(d):
591 update_list.append(d)
596 if str(c).lower() == str(d).lower():
602 if not opts.all_names and not check_dns_name(c):
604 delete_list.append(c)
606 if len(delete_list) == 0 and len(update_list) == 0 and not rebuild_cache:
608 print "No DNS updates needed"
612 if len(delete_list) != 0 or len(update_list) != 0:
616 # ask nsupdate to delete entries as needed
617 for d in delete_list:
619 if d.name.lower() == domain.lower():
621 if not d.type in [ 'A', 'AAAA' ]:
622 call_rodc_update(d, op="delete")
624 call_nsupdate(d, op="delete")
626 call_nsupdate(d, op="delete")
628 # ask nsupdate to add entries as needed
629 for d in update_list:
631 if d.name.lower() == domain.lower():
633 if not d.type in [ 'A', 'AAAA' ]:
641 (file_dir, file_name) = os.path.split(dns_update_cache)
642 (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
643 wfile = os.fdopen(tmp_fd, 'a')
645 wfile.write(str(d)+"\n")
646 os.rename(tmpfile, dns_update_cache)
647 fcntl.lockf(cfile, fcntl.LOCK_UN)
649 # delete the ccache if we created it
650 if ccachename is not None:
651 os.unlink(ccachename)
654 print("Failed update of %u entries" % error_count)
655 sys.exit(error_count)