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
49 from samba.netcmd.dns import cmd_dns
50 from samba import gensec
52 samba.ensure_third_party_module("dns", "dnspython")
60 parser = optparse.OptionParser("samba_dnsupdate")
61 sambaopts = options.SambaOptions(parser)
62 parser.add_option_group(sambaopts)
63 parser.add_option_group(options.VersionOptions(parser))
64 parser.add_option("--verbose", action="store_true")
65 parser.add_option("--use-samba-tool", action="store_true", help="Use samba-tool to make updates over RPC, rather than over DNS")
66 parser.add_option("--use-nsupdate", action="store_true", help="Use nsupdate command to make updates over DNS (default, if kinit successful)")
67 parser.add_option("--all-names", action="store_true")
68 parser.add_option("--all-interfaces", action="store_true")
69 parser.add_option("--current-ip", action="append", help="IP address to update DNS to match (helpful if behind NAT, valid multiple times, defaults to values from interfaces=)")
70 parser.add_option("--rpc-server-ip", type="string", help="IP address of server to use with samba-tool (defaults to first --current-ip)")
71 parser.add_option("--use-file", type="string", help="Use a file, rather than real DNS calls")
72 parser.add_option("--update-list", type="string", help="Add DNS names from the given file")
73 parser.add_option("--update-cache", type="string", help="Cache database of already registered records")
74 parser.add_option("--fail-immediately", action='store_true', help="Exit on first failure")
75 parser.add_option("--no-credentials", dest='nocreds', action='store_true', help="don't try and get credentials")
76 parser.add_option("--no-substitutions", dest='nosubs', action='store_true', help="don't try and expands variables in file specified by --update-list")
81 opts, args = parser.parse_args()
87 lp = sambaopts.get_loadparm()
89 domain = lp.get("realm")
90 host = lp.get("netbios name")
91 if opts.all_interfaces:
94 all_interfaces = False
99 IPs = samba.interface_ips(lp, all_interfaces)
101 nsupdate_cmd = lp.get('nsupdate command')
104 print "No IP interfaces - skipping DNS updates"
107 if opts.rpc_server_ip:
108 rpc_server_ip = opts.rpc_server_ip
110 rpc_server_ip = IPs[0]
115 if i.find(':') != -1:
122 print "IPs: %s" % IPs
125 def get_credentials(lp):
126 """# get credentials if we haven't got them already."""
127 from samba import credentials
129 creds = credentials.Credentials()
131 creds.set_machine_account(lp)
132 creds.set_krb_forwardable(credentials.NO_KRB_FORWARDABLE)
133 (tmp_fd, ccachename) = tempfile.mkstemp()
135 creds.get_named_ccache(lp, ccachename)
137 if opts.use_file is not None:
140 # Now confirm we can get a ticket to a DNS server
141 ans = check_one_dns_name(sub_vars['DNSDOMAIN'] + '.', 'NS')
142 for i in range(len(ans)):
143 target_hostname = str(ans[i].target).rstrip('.')
145 settings["lp_ctx"] = lp
146 settings["target_hostname"] = target_hostname
148 gensec_client = gensec.Security.start_client(settings)
149 gensec_client.set_credentials(creds)
150 gensec_client.set_target_service("DNS")
151 gensec_client.set_target_hostname(target_hostname)
152 gensec_client.want_feature(gensec.FEATURE_SEAL)
153 gensec_client.start_mech_by_sasl_name("GSSAPI")
154 server_to_client = ""
156 (client_finished, client_to_server) = gensec_client.update(server_to_client)
158 print "Successfully obtained Kerberos ticket to DNS/%s as %s" \
159 % (target_hostname, creds.get_username())
162 # Only raise an exception if they all failed
163 if i != len(ans) - 1:
167 except RuntimeError as e:
168 os.unlink(ccachename)
172 class dnsobj(object):
173 """an object to hold a parsed DNS line"""
175 def __init__(self, string_form):
176 list = string_form.split()
178 raise Exception("Invalid DNS entry %r" % string_form)
182 self.existing_port = None
183 self.existing_weight = None
184 self.existing_cname_target = None
187 self.nameservers = []
188 if self.type == 'SRV':
190 raise Exception("Invalid DNS entry %r" % string_form)
193 elif self.type in ['A', 'AAAA']:
194 self.ip = list[2] # usually $IP, which gets replaced
195 elif self.type == 'CNAME':
197 elif self.type == 'NS':
200 raise Exception("Received unexpected DNS reply of type %s: %s" % (self.type, string_form))
204 return "%s %s %s" % (self.type, self.name, self.ip)
205 if self.type == "AAAA":
206 return "%s %s %s" % (self.type, self.name, self.ip)
207 if self.type == "SRV":
208 return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
209 if self.type == "CNAME":
210 return "%s %s %s" % (self.type, self.name, self.dest)
211 if self.type == "NS":
212 return "%s %s %s" % (self.type, self.name, self.dest)
215 def parse_dns_line(line, sub_vars):
216 """parse a DNS line from."""
217 if line.startswith("SRV _ldap._tcp.pdc._msdcs.") and not samdb.am_pdc():
218 # We keep this as compat to the dns_update_list of 4.0/4.1
220 print "Skipping PDC entry (%s) as we are not a PDC" % line
222 subline = samba.substitute_var(line, sub_vars)
223 if subline == '' or subline[0] == "#":
225 return dnsobj(subline)
228 def hostname_match(h1, h2):
229 """see if two hostnames match."""
232 return h1.lower().rstrip('.') == h2.lower().rstrip('.')
234 def check_one_dns_name(name, name_type, d=None):
235 resolv_conf = os.getenv('RESOLV_WRAPPER_CONF')
237 resolv_conf = '/etc/resolv.conf'
238 resolver = dns.resolver.Resolver(filename=resolv_conf, configure=True)
240 if d is not None and d.nameservers != []:
241 resolver.nameservers = d.nameservers
243 d.nameservers = resolver.nameservers
245 ans = resolver.query(name, name_type)
248 def check_dns_name(d):
249 """check that a DNS entry exists."""
250 normalised_name = d.name.rstrip('.') + '.'
252 print "Looking for DNS entry %s as %s" % (d, normalised_name)
254 if opts.use_file is not None:
256 dns_file = open(opts.use_file, "r")
260 for line in dns_file:
262 if line == '' or line[0] == "#":
264 if line.lower() == str(d).lower():
269 ans = check_one_dns_name(normalised_name, d.type, d)
270 except dns.exception.DNSException:
272 print "Failed to find DNS entry %s" % d
274 if d.type in ['A', 'AAAA']:
275 # we need to be sure that our IP is there
277 if str(rdata) == str(d.ip):
279 elif d.type == 'CNAME':
280 for i in range(len(ans)):
281 if hostname_match(ans[i].target, d.dest):
284 d.existing_cname_target = str(ans[i].target)
286 for i in range(len(ans)):
287 if hostname_match(ans[i].target, d.dest):
289 elif d.type == 'SRV':
292 print "Checking %s against %s" % (rdata, d)
293 if hostname_match(rdata.target, d.dest):
294 if str(rdata.port) == str(d.port):
297 d.existing_port = str(rdata.port)
298 d.existing_weight = str(rdata.weight)
301 print "Failed to find matching DNS entry %s" % d
306 def get_subst_vars(samdb):
307 """get the list of substitution vars."""
311 vars['DNSDOMAIN'] = samdb.domain_dns_name()
312 vars['DNSFOREST'] = samdb.forest_dns_name()
313 vars['HOSTNAME'] = samdb.host_dns_name()
314 vars['NTDSGUID'] = samdb.get_ntds_GUID()
315 vars['SITE'] = samdb.server_site_name()
316 res = samdb.search(base=samdb.get_default_basedn(), scope=SCOPE_BASE, attrs=["objectGUID"])
317 guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
318 vars['DOMAINGUID'] = guid
321 vars['IF_RWDC'] = "# "
322 vars['IF_RODC'] = "# "
323 vars['IF_PDC'] = "# "
325 vars['IF_RWGC'] = "# "
326 vars['IF_ROGC'] = "# "
327 vars['IF_DNS_DOMAIN'] = "# "
328 vars['IF_RWDNS_DOMAIN'] = "# "
329 vars['IF_RODNS_DOMAIN'] = "# "
330 vars['IF_DNS_FOREST'] = "# "
331 vars['IF_RWDNS_FOREST'] = "# "
332 vars['IF_R0DNS_FOREST'] = "# "
334 am_rodc = samdb.am_rodc()
343 # check if we "are DNS server"
344 res = samdb.search(base=samdb.get_config_basedn(),
345 expression='(objectguid=%s)' % vars['NTDSGUID'],
346 attrs=["options", "msDS-hasMasterNCs"])
349 if "options" in res[0]:
350 options = int(res[0]["options"][0])
351 if (options & dsdb.DS_NTDSDSA_OPT_IS_GC) != 0:
358 basedn = str(samdb.get_default_basedn())
359 forestdn = str(samdb.get_root_basedn())
361 if "msDS-hasMasterNCs" in res[0]:
362 for e in res[0]["msDS-hasMasterNCs"]:
363 if str(e) == "DC=DomainDnsZones,%s" % basedn:
364 vars['IF_DNS_DOMAIN'] = ""
366 vars['IF_RODNS_DOMAIN'] = ""
368 vars['IF_RWDNS_DOMAIN'] = ""
369 if str(e) == "DC=ForestDnsZones,%s" % forestdn:
370 vars['IF_DNS_FOREST'] = ""
372 vars['IF_RODNS_FOREST'] = ""
374 vars['IF_RWDNS_FOREST'] = ""
379 def call_nsupdate(d, op="add"):
380 """call nsupdate for an entry."""
381 global ccachename, nsupdate_cmd, krb5conf
383 assert(op in ["add", "delete"])
386 print "Calling nsupdate for %s (%s)" % (d, op)
388 if opts.use_file is not None:
390 rfile = open(opts.use_file, 'r+')
393 rfile = open(opts.use_file, 'w+')
394 # Open it for reading again, in case someone else got to it first
395 rfile = open(opts.use_file, 'r+')
396 fcntl.lockf(rfile, fcntl.LOCK_EX)
397 (file_dir, file_name) = os.path.split(opts.use_file)
398 (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
399 wfile = os.fdopen(tmp_fd, 'a')
403 l = parse_dns_line(line, {})
404 if str(l).lower() == str(d).lower():
408 wfile.write(str(d)+"\n")
409 os.rename(tmpfile, opts.use_file)
410 fcntl.lockf(rfile, fcntl.LOCK_UN)
413 normalised_name = d.name.rstrip('.') + '.'
415 (tmp_fd, tmpfile) = tempfile.mkstemp()
416 f = os.fdopen(tmp_fd, 'w')
417 if d.nameservers != []:
418 f.write('server %s\n' % d.nameservers[0])
420 f.write("update %s %s %u A %s\n" % (op, normalised_name, default_ttl, d.ip))
422 f.write("update %s %s %u AAAA %s\n" % (op, normalised_name, default_ttl, d.ip))
424 if op == "add" and d.existing_port is not None:
425 f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
426 d.existing_port, d.dest))
427 f.write("update %s %s %u SRV 0 100 %s %s\n" % (op, normalised_name, default_ttl, d.port, d.dest))
428 if d.type == "CNAME":
429 f.write("update %s %s %u CNAME %s\n" % (op, normalised_name, default_ttl, d.dest))
431 f.write("update %s %s %u NS %s\n" % (op, normalised_name, default_ttl, d.dest))
437 # Set a bigger MTU size to work around a bug in nsupdate's doio_send()
438 os.environ["SOCKET_WRAPPER_MTU"] = "2000"
442 os.environ["KRB5CCNAME"] = ccachename
444 cmd = nsupdate_cmd[:]
448 env["KRB5_CONFIG"] = krb5conf
450 env["KRB5CCNAME"] = ccachename
451 ret = subprocess.call(cmd, shell=False, env=env)
453 if opts.fail_immediately:
455 print("Failed update with %s" % tmpfile)
457 error_count = error_count + 1
459 print("Failed nsupdate: %d" % ret)
460 except Exception, estr:
461 if opts.fail_immediately:
463 error_count = error_count + 1
465 print("Failed nsupdate: %s : %s" % (str(d), estr))
468 # Let socket_wrapper set the default MTU size
469 os.environ["SOCKET_WRAPPER_MTU"] = "0"
472 def call_samba_tool(d, op="add"):
473 """call samba-tool dns to update an entry."""
475 assert(op in ["add", "delete"])
477 if (sub_vars['DNSFOREST'] != sub_vars['DNSDOMAIN']) and \
478 sub_vars['DNSFOREST'].endswith('.' + sub_vars['DNSDOMAIN']):
479 print "Refusing to use samba-tool when forest %s is under domain %s" \
480 % (sub_vars['DNSFOREST'], sub_vars['DNSDOMAIN'])
483 print "Calling samba-tool dns for %s (%s)" % (d, op)
485 normalised_name = d.name.rstrip('.') + '.'
486 if normalised_name == (sub_vars['DNSDOMAIN'] + '.'):
488 zone = sub_vars['DNSDOMAIN']
489 elif normalised_name == (sub_vars['DNSFOREST'] + '.'):
491 zone = sub_vars['DNSFOREST']
492 elif normalised_name == ('_msdcs.' + sub_vars['DNSFOREST'] + '.'):
494 zone = '_msdcs.' + sub_vars['DNSFOREST']
496 if not normalised_name.endswith('.' + sub_vars['DNSDOMAIN'] + '.'):
497 print "Not Calling samba-tool dns for %s (%s), %s not in %s" % (d, op, normalised_name, sub_vars['DNSDOMAIN'] + '.')
499 elif normalised_name.endswith('._msdcs.' + sub_vars['DNSFOREST'] + '.'):
500 zone = '_msdcs.' + sub_vars['DNSFOREST']
502 zone = sub_vars['DNSDOMAIN']
503 len_zone = len(zone)+2
504 short_name = normalised_name[:-len_zone]
507 args = [rpc_server_ip, zone, short_name, "A", d.ip]
509 args = [rpc_server_ip, zone, short_name, "AAAA", d.ip]
511 if op == "add" and d.existing_port is not None:
512 print "Not handling modify of exising SRV %s using samba-tool" % d
515 args = [rpc_server_ip, zone, short_name, "SRV",
516 "%s %s %s %s" % (d.existing_weight,
517 d.existing_port, "0", "100"),
518 "%s %s %s %s" % (d.dest, d.port, "0", "100")]
520 args = [rpc_server_ip, zone, short_name, "SRV", "%s %s %s %s" % (d.dest, d.port, "0", "100")]
521 if d.type == "CNAME":
522 if d.existing_cname_target is None:
523 args = [rpc_server_ip, zone, short_name, "CNAME", d.dest]
526 args = [rpc_server_ip, zone, short_name, "CNAME",
527 d.existing_cname_target.rstrip('.'), d.dest]
530 args = [rpc_server_ip, zone, short_name, "NS", d.dest]
536 print "Calling samba-tool dns %s -k no -P %s" % (op, args)
537 cmd._run("dns", op, "-k", "no", "-P", *args)
538 except Exception, estr:
540 if opts.fail_immediately:
542 error_count = error_count + 1
544 print("Failed 'samba-tool dns' based update: %s : %s" % (str(d), estr))
546 def rodc_dns_update(d, t, op):
547 '''a single DNS update via the RODC netlogon call'''
550 assert(op in ["add", "delete"])
553 print "Calling netlogon RODC update for %s" % d
556 netlogon.NlDnsLdapAtSite : netlogon.NlDnsInfoTypeNone,
557 netlogon.NlDnsGcAtSite : netlogon.NlDnsDomainNameAlias,
558 netlogon.NlDnsDsaCname : netlogon.NlDnsDomainNameAlias,
559 netlogon.NlDnsKdcAtSite : netlogon.NlDnsInfoTypeNone,
560 netlogon.NlDnsDcAtSite : netlogon.NlDnsInfoTypeNone,
561 netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
562 netlogon.NlDnsGenericGcAtSite : netlogon.NlDnsDomainNameAlias
565 w = winbind.winbind("irpc:winbind_server", lp)
566 dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
568 name = netlogon.NL_DNS_NAME_INFO()
570 name.dns_domain_info_type = typemap[t]
573 if d.port is not None:
574 name.port = int(d.port)
576 name.dns_register = True
578 name.dns_register = False
579 dns_names.names = [ name ]
580 site_name = sub_vars['SITE'].decode('utf-8')
585 ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
586 if ret_names.names[0].status != 0:
587 print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
588 error_count = error_count + 1
589 except RuntimeError, reason:
590 print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
591 error_count = error_count + 1
593 if error_count != 0 and opts.fail_immediately:
597 def call_rodc_update(d, op="add"):
598 '''RODCs need to use the netlogon API for nsupdate'''
601 assert(op in ["add", "delete"])
603 # we expect failure for 3268 if we aren't a GC
604 if d.port is not None and int(d.port) == 3268:
607 # map the DNS request to a netlogon update type
609 netlogon.NlDnsLdapAtSite : '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
610 netlogon.NlDnsGcAtSite : '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
611 netlogon.NlDnsDsaCname : '${NTDSGUID}._msdcs.${DNSFOREST}',
612 netlogon.NlDnsKdcAtSite : '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
613 netlogon.NlDnsDcAtSite : '_ldap._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
614 netlogon.NlDnsRfc1510KdcAtSite : '_kerberos._tcp.${SITE}._sites.${DNSDOMAIN}',
615 netlogon.NlDnsGenericGcAtSite : '_gc._tcp.${SITE}._sites.${DNSFOREST}'
619 subname = samba.substitute_var(map[t], sub_vars)
620 if subname.lower() == d.name.lower():
621 # found a match - do the update
622 rodc_dns_update(d, t, op)
625 print("Unable to map to netlogon DNS update: %s" % d)
628 # get the list of DNS entries we should have
630 dns_update_list = opts.update_list
632 dns_update_list = lp.private_path('dns_update_list')
634 if opts.update_cache:
635 dns_update_cache = opts.update_cache
637 dns_update_cache = lp.private_path('dns_update_cache')
639 # use our private krb5.conf to avoid problems with the wrong domain
640 # bind9 nsupdate wants the default domain set
641 krb5conf = lp.private_path('krb5.conf')
642 os.environ['KRB5_CONFIG'] = krb5conf
644 file = open(dns_update_list, "r")
649 samdb = SamDB(url=lp.samdb_url(), session_info=system_session(), lp=lp)
651 # get the substitution dictionary
652 sub_vars = get_subst_vars(samdb)
654 # build up a list of update commands to pass to nsupdate
663 rebuild_cache = False
665 cfile = open(dns_update_cache, 'r+')
668 cfile = open(dns_update_cache, 'w+')
669 # Open it for reading again, in case someone else got to it first
670 cfile = open(dns_update_cache, 'r+')
671 fcntl.lockf(cfile, fcntl.LOCK_EX)
674 if line == '' or line[0] == "#":
676 c = parse_dns_line(line, {})
679 if str(c) not in cache_set:
681 cache_set.add(str(c))
683 # read each line, and check that the DNS name exists
686 if line == '' or line[0] == "#":
688 d = parse_dns_line(line, sub_vars)
691 if d.type == 'A' and len(IP4s) == 0:
693 if d.type == 'AAAA' and len(IP6s) == 0:
695 if str(d) not in dup_set:
699 # now expand the entries, if any are A record with ip set to $IP
700 # then replace with multiple entries, one for each interface IP
706 for i in range(len(IP4s)-1):
712 for i in range(len(IP6s)-1):
717 # now check if the entries already exist on the DNS server
721 if str(c).lower() == str(d).lower():
727 update_list.append(d)
729 print "force update: %s" % d
730 elif not check_dns_name(d):
731 update_list.append(d)
733 print "need update: %s" % d
739 if str(c).lower() == str(d).lower():
745 if not opts.all_names and not check_dns_name(c):
747 delete_list.append(c)
749 print "need delete: %s" % c
751 if len(delete_list) == 0 and len(update_list) == 0 and not rebuild_cache:
753 print "No DNS updates needed"
757 print "%d DNS updates and %d DNS deletes needed" % (len(update_list), len(delete_list))
759 use_samba_tool = opts.use_samba_tool
760 use_nsupdate = opts.use_nsupdate
762 if len(delete_list) != 0 or len(update_list) != 0 and not opts.nocreds:
764 creds = get_credentials(lp)
765 except RuntimeError as e:
768 if sub_vars['IF_RWDNS_DOMAIN'] == "# ":
774 print "Failed to get Kerberos credentials, falling back to samba-tool: %s" % e
775 use_samba_tool = True
778 # ask nsupdate to delete entries as needed
779 for d in delete_list:
780 if not use_nsupdate and use_samba_tool:
781 call_samba_tool(d, op="delete")
784 if d.name.lower() == domain.lower():
786 print "skip delete (rodc): %s" % d
788 if not d.type in [ 'A', 'AAAA' ]:
790 print "delete (rodc): %s" % d
791 call_rodc_update(d, op="delete")
794 print "delete (nsupdate): %s" % d
795 call_nsupdate(d, op="delete")
798 print "delete (nsupdate): %s" % d
799 call_nsupdate(d, op="delete")
801 # ask nsupdate to add entries as needed
802 for d in update_list:
803 if not use_nsupdate and use_samba_tool:
807 if d.name.lower() == domain.lower():
809 print "skip (rodc): %s" % d
811 if not d.type in [ 'A', 'AAAA' ]:
813 print "update (rodc): %s" % d
817 print "update (nsupdate): %s" % d
821 print "update(nsupdate): %s" % d
825 (file_dir, file_name) = os.path.split(dns_update_cache)
826 (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
827 wfile = os.fdopen(tmp_fd, 'a')
829 wfile.write(str(d)+"\n")
830 os.rename(tmpfile, dns_update_cache)
831 fcntl.lockf(cfile, fcntl.LOCK_UN)
833 # delete the ccache if we created it
834 if ccachename is not None:
835 os.unlink(ccachename)
838 print("Failed update of %u entries" % error_count)
839 sys.exit(error_count)