s4:samba_dnsupdate: don't try to be smart when verifying NS records
[Samba.git] / source4 / scripting / bin / samba_dnsupdate
blob0d001ac9145effd0dd3436dc0e652a0f9882e07b
1 #!/usr/bin/env python
2 # vim: expandtab
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/>.
22 import os
23 import fcntl
24 import sys
25 import tempfile
26 import subprocess
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
35 # the US)
36 os.environ["TZ"] = "GMT"
38 # Find right directory when running from source tree
39 sys.path.insert(0, "bin/python")
41 import samba
42 import optparse
43 from samba import getopt as options
44 from ldb import SCOPE_BASE
45 from samba.auth import system_session
46 from samba.samdb import SamDB
47 from samba.dcerpc import netlogon, winbind
49 samba.ensure_external_module("dns", "dnspython")
50 import dns.resolver
51 import dns.exception
53 default_ttl = 900
54 am_rodc = False
55 error_count = 0
57 parser = optparse.OptionParser("samba_dnsupdate")
58 sambaopts = options.SambaOptions(parser)
59 parser.add_option_group(sambaopts)
60 parser.add_option_group(options.VersionOptions(parser))
61 parser.add_option("--verbose", action="store_true")
62 parser.add_option("--all-names", action="store_true")
63 parser.add_option("--all-interfaces", action="store_true")
64 parser.add_option("--use-file", type="string", help="Use a file, rather than real DNS calls")
65 parser.add_option("--update-list", type="string", help="Add DNS names from the given file")
66 parser.add_option("--update-cache", type="string", help="Cache database of already registered records")
67 parser.add_option("--fail-immediately", action='store_true', help="Exit on first failure")
68 parser.add_option("--no-credentials", dest='nocreds', action='store_true', help="don't try and get credentials")
69 parser.add_option("--no-substiutions", dest='nosubs', action='store_true', help="don't try and expands variables in file specified by --update-list")
71 creds = None
72 ccachename = None
74 opts, args = parser.parse_args()
76 if len(args) != 0:
77 parser.print_usage()
78 sys.exit(1)
80 lp = sambaopts.get_loadparm()
82 domain = lp.get("realm")
83 host = lp.get("netbios name")
84 if opts.all_interfaces:
85 all_interfaces = True
86 else:
87 all_interfaces = False
89 IPs = samba.interface_ips(lp, all_interfaces)
90 nsupdate_cmd = lp.get('nsupdate command')
92 if len(IPs) == 0:
93 print "No IP interfaces - skipping DNS updates"
94 sys.exit(0)
96 IP6s = []
97 IP4s = []
98 for i in IPs:
99 if i.find(':') != -1:
100 IP6s.append(i)
101 else:
102 IP4s.append(i)
105 if opts.verbose:
106 print "IPs: %s" % IPs
109 def get_credentials(lp):
110 """# get credentials if we haven't got them already."""
111 from samba import credentials
112 global ccachename, creds
113 if creds is not None:
114 return
115 creds = credentials.Credentials()
116 creds.guess(lp)
117 creds.set_machine_account(lp)
118 creds.set_krb_forwardable(credentials.NO_KRB_FORWARDABLE)
119 (tmp_fd, ccachename) = tempfile.mkstemp()
120 try:
121 creds.get_named_ccache(lp, ccachename)
122 except RuntimeError as e:
123 os.unlink(ccachename)
124 raise e
127 class dnsobj(object):
128 """an object to hold a parsed DNS line"""
130 def __init__(self, string_form):
131 list = string_form.split()
132 if len(list) < 3:
133 raise Exception("Invalid DNS entry %r" % string_form)
134 self.dest = None
135 self.port = None
136 self.ip = None
137 self.existing_port = None
138 self.existing_weight = None
139 self.type = list[0]
140 self.name = list[1]
141 if self.type == 'SRV':
142 if len(list) < 4:
143 raise Exception("Invalid DNS entry %r" % string_form)
144 self.dest = list[2]
145 self.port = list[3]
146 elif self.type in ['A', 'AAAA']:
147 self.ip = list[2] # usually $IP, which gets replaced
148 elif self.type == 'CNAME':
149 self.dest = list[2]
150 elif self.type == 'NS':
151 self.dest = list[2]
152 else:
153 raise Exception("Received unexpected DNS reply of type %s: %s" % (self.type, string_form))
155 def __str__(self):
156 if self.type == "A":
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 if opts.verbose:
172 print "Skipping PDC entry (%s) as we are not a PDC" % line
173 return None
174 subline = samba.substitute_var(line, sub_vars)
175 return dnsobj(subline)
178 def hostname_match(h1, h2):
179 """see if two hostnames match."""
180 h1 = str(h1)
181 h2 = str(h2)
182 return h1.lower().rstrip('.') == h2.lower().rstrip('.')
185 def check_dns_name(d):
186 """check that a DNS entry exists."""
187 normalised_name = d.name.rstrip('.') + '.'
188 if opts.verbose:
189 print "Looking for DNS entry %s as %s" % (d, normalised_name)
191 if opts.use_file is not None:
192 try:
193 dns_file = open(opts.use_file, "r")
194 except IOError:
195 return False
197 for line in dns_file:
198 line = line.strip()
199 if line == '' or line[0] == "#":
200 continue
201 if line.lower() == str(d).lower():
202 return True
203 return False
205 resolver = dns.resolver.Resolver()
207 try:
208 if getattr(d, 'nameservers', None):
209 resolver.nameservers = list(d.nameservers)
210 ans = resolver.query(normalised_name, d.type)
211 except dns.exception.DNSException:
212 if opts.verbose:
213 print "Failed to find DNS entry %s" % d
214 return False
215 if d.type in ['A', 'AAAA']:
216 # we need to be sure that our IP is there
217 for rdata in ans:
218 if str(rdata) == str(d.ip):
219 return True
220 elif d.type == 'CNAME':
221 for i in range(len(ans)):
222 if hostname_match(ans[i].target, d.dest):
223 return True
224 elif d.type == 'NS':
225 for i in range(len(ans)):
226 if hostname_match(ans[i].target, d.dest):
227 return True
228 elif d.type == 'SRV':
229 for rdata in ans:
230 if opts.verbose:
231 print "Checking %s against %s" % (rdata, d)
232 if hostname_match(rdata.target, d.dest):
233 if str(rdata.port) == str(d.port):
234 return True
235 else:
236 d.existing_port = str(rdata.port)
237 d.existing_weight = str(rdata.weight)
239 if opts.verbose:
240 print "Failed to find matching DNS entry %s" % d
242 return False
245 def get_subst_vars(samdb):
246 """get the list of substitution vars."""
247 global lp, am_rodc
248 vars = {}
250 vars['DNSDOMAIN'] = samdb.domain_dns_name()
251 vars['DNSFOREST'] = samdb.forest_dns_name()
252 vars['HOSTNAME'] = samdb.host_dns_name()
253 vars['NTDSGUID'] = samdb.get_ntds_GUID()
254 vars['SITE'] = samdb.server_site_name()
255 res = samdb.search(base=samdb.get_default_basedn(), scope=SCOPE_BASE, attrs=["objectGUID"])
256 guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
257 vars['DOMAINGUID'] = guid
258 am_rodc = samdb.am_rodc()
260 return vars
263 def call_nsupdate(d, op="add"):
264 """call nsupdate for an entry."""
265 global ccachename, nsupdate_cmd, krb5conf
267 assert(op in ["add", "delete"])
269 if opts.verbose:
270 print "Calling nsupdate for %s (%s)" % (d, op)
272 if opts.use_file is not None:
273 try:
274 rfile = open(opts.use_file, 'r+')
275 except IOError:
276 # Perhaps create it
277 rfile = open(opts.use_file, 'w+')
278 # Open it for reading again, in case someone else got to it first
279 rfile = open(opts.use_file, 'r+')
280 fcntl.lockf(rfile, fcntl.LOCK_EX)
281 (file_dir, file_name) = os.path.split(opts.use_file)
282 (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
283 wfile = os.fdopen(tmp_fd, 'a')
284 rfile.seek(0)
285 for line in rfile:
286 if op == "delete":
287 l = parse_dns_line(line, {})
288 if str(l).lower() == str(d).lower():
289 continue
290 wfile.write(line)
291 if op == "add":
292 wfile.write(str(d)+"\n")
293 os.rename(tmpfile, opts.use_file)
294 fcntl.lockf(rfile, fcntl.LOCK_UN)
295 return
297 normalised_name = d.name.rstrip('.') + '.'
299 (tmp_fd, tmpfile) = tempfile.mkstemp()
300 f = os.fdopen(tmp_fd, 'w')
301 if getattr(d, 'nameservers', None):
302 f.write('server %s\n' % d.nameservers[0])
303 if d.type == "A":
304 f.write("update %s %s %u A %s\n" % (op, normalised_name, default_ttl, d.ip))
305 if d.type == "AAAA":
306 f.write("update %s %s %u AAAA %s\n" % (op, normalised_name, default_ttl, d.ip))
307 if d.type == "SRV":
308 if op == "add" and d.existing_port is not None:
309 f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
310 d.existing_port, d.dest))
311 f.write("update %s %s %u SRV 0 100 %s %s\n" % (op, normalised_name, default_ttl, d.port, d.dest))
312 if d.type == "CNAME":
313 f.write("update %s %s %u CNAME %s\n" % (op, normalised_name, default_ttl, d.dest))
314 if d.type == "NS":
315 f.write("update %s %s %u NS %s\n" % (op, normalised_name, default_ttl, d.dest))
316 if opts.verbose:
317 f.write("show\n")
318 f.write("send\n")
319 f.close()
321 global error_count
322 if ccachename:
323 os.environ["KRB5CCNAME"] = ccachename
324 try:
325 cmd = nsupdate_cmd[:]
326 cmd.append(tmpfile)
327 env = {}
328 if krb5conf:
329 env["KRB5_CONFIG"] = krb5conf
330 if ccachename:
331 env["KRB5CCNAME"] = ccachename
332 ret = subprocess.call(cmd, shell=False, env=env)
333 if ret != 0:
334 if opts.fail_immediately:
335 if opts.verbose:
336 print("Failed update with %s" % tmpfile)
337 sys.exit(1)
338 error_count = error_count + 1
339 if opts.verbose:
340 print("Failed nsupdate: %d" % ret)
341 except Exception, estr:
342 if opts.fail_immediately:
343 sys.exit(1)
344 error_count = error_count + 1
345 if opts.verbose:
346 print("Failed nsupdate: %s : %s" % (str(d), estr))
347 os.unlink(tmpfile)
351 def rodc_dns_update(d, t, op):
352 '''a single DNS update via the RODC netlogon call'''
353 global sub_vars
355 assert(op in ["add", "delete"])
357 if opts.verbose:
358 print "Calling netlogon RODC update for %s" % d
360 typemap = {
361 netlogon.NlDnsLdapAtSite : netlogon.NlDnsInfoTypeNone,
362 netlogon.NlDnsGcAtSite : netlogon.NlDnsDomainNameAlias,
363 netlogon.NlDnsDsaCname : netlogon.NlDnsDomainNameAlias,
364 netlogon.NlDnsKdcAtSite : netlogon.NlDnsInfoTypeNone,
365 netlogon.NlDnsDcAtSite : netlogon.NlDnsInfoTypeNone,
366 netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
367 netlogon.NlDnsGenericGcAtSite : netlogon.NlDnsDomainNameAlias
370 w = winbind.winbind("irpc:winbind_server", lp)
371 dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
372 dns_names.count = 1
373 name = netlogon.NL_DNS_NAME_INFO()
374 name.type = t
375 name.dns_domain_info_type = typemap[t]
376 name.priority = 0
377 name.weight = 0
378 if d.port is not None:
379 name.port = int(d.port)
380 if op == "add":
381 name.dns_register = True
382 else:
383 name.dns_register = False
384 dns_names.names = [ name ]
385 site_name = sub_vars['SITE'].decode('utf-8')
387 global error_count
389 try:
390 ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
391 if ret_names.names[0].status != 0:
392 print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
393 error_count = error_count + 1
394 except RuntimeError, reason:
395 print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
396 error_count = error_count + 1
398 if error_count != 0 and opts.fail_immediately:
399 sys.exit(1)
402 def call_rodc_update(d, op="add"):
403 '''RODCs need to use the netlogon API for nsupdate'''
404 global lp, sub_vars
406 assert(op in ["add", "delete"])
408 # we expect failure for 3268 if we aren't a GC
409 if d.port is not None and int(d.port) == 3268:
410 return
412 # map the DNS request to a netlogon update type
413 map = {
414 netlogon.NlDnsLdapAtSite : '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
415 netlogon.NlDnsGcAtSite : '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
416 netlogon.NlDnsDsaCname : '${NTDSGUID}._msdcs.${DNSFOREST}',
417 netlogon.NlDnsKdcAtSite : '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
418 netlogon.NlDnsDcAtSite : '_ldap._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
419 netlogon.NlDnsRfc1510KdcAtSite : '_kerberos._tcp.${SITE}._sites.${DNSDOMAIN}',
420 netlogon.NlDnsGenericGcAtSite : '_gc._tcp.${SITE}._sites.${DNSFOREST}'
423 for t in map:
424 subname = samba.substitute_var(map[t], sub_vars)
425 if subname.lower() == d.name.lower():
426 # found a match - do the update
427 rodc_dns_update(d, t, op)
428 return
429 if opts.verbose:
430 print("Unable to map to netlogon DNS update: %s" % d)
433 # get the list of DNS entries we should have
434 if opts.update_list:
435 dns_update_list = opts.update_list
436 else:
437 dns_update_list = lp.private_path('dns_update_list')
439 if opts.update_cache:
440 dns_update_cache = opts.update_cache
441 else:
442 dns_update_cache = lp.private_path('dns_update_cache')
444 # use our private krb5.conf to avoid problems with the wrong domain
445 # bind9 nsupdate wants the default domain set
446 krb5conf = lp.private_path('krb5.conf')
447 os.environ['KRB5_CONFIG'] = krb5conf
449 file = open(dns_update_list, "r")
451 if opts.nosubs:
452 sub_vars = {}
453 else:
454 samdb = SamDB(url=lp.samdb_url(), session_info=system_session(), lp=lp)
456 # get the substitution dictionary
457 sub_vars = get_subst_vars(samdb)
459 # build up a list of update commands to pass to nsupdate
460 update_list = []
461 dns_list = []
462 cache_list = []
463 delete_list = []
465 dup_set = set()
466 cache_set = set()
468 rebuild_cache = False
469 try:
470 cfile = open(dns_update_cache, 'r+')
471 except IOError:
472 # Perhaps create it
473 cfile = open(dns_update_cache, 'w+')
474 # Open it for reading again, in case someone else got to it first
475 cfile = open(dns_update_cache, 'r+')
476 fcntl.lockf(cfile, fcntl.LOCK_EX)
477 for line in cfile:
478 line = line.strip()
479 if line == '' or line[0] == "#":
480 continue
481 c = parse_dns_line(line, {})
482 if c is None:
483 continue
484 if str(c) not in cache_set:
485 cache_list.append(c)
486 cache_set.add(str(c))
488 # read each line, and check that the DNS name exists
489 for line in file:
490 line = line.strip()
491 if line == '' or line[0] == "#":
492 continue
493 d = parse_dns_line(line, sub_vars)
494 if d is None:
495 continue
496 if d.type == 'A' and len(IP4s) == 0:
497 continue
498 if d.type == 'AAAA' and len(IP6s) == 0:
499 continue
500 if str(d) not in dup_set:
501 dns_list.append(d)
502 dup_set.add(str(d))
504 # now expand the entries, if any are A record with ip set to $IP
505 # then replace with multiple entries, one for each interface IP
506 for d in dns_list:
507 if d.ip != "$IP":
508 continue
509 if d.type == 'A':
510 d.ip = IP4s[0]
511 for i in range(len(IP4s)-1):
512 d2 = dnsobj(str(d))
513 d2.ip = IP4s[i+1]
514 dns_list.append(d2)
515 if d.type == 'AAAA':
516 d.ip = IP6s[0]
517 for i in range(len(IP6s)-1):
518 d2 = dnsobj(str(d))
519 d2.ip = IP6s[i+1]
520 dns_list.append(d2)
522 # now check if the entries already exist on the DNS server
523 for d in dns_list:
524 found = False
525 for c in cache_list:
526 if str(c).lower() == str(d).lower():
527 found = True
528 break
529 if not found:
530 rebuild_cache = True
531 if opts.all_names or not check_dns_name(d):
532 update_list.append(d)
534 for c in cache_list:
535 found = False
536 for d in dns_list:
537 if str(c).lower() == str(d).lower():
538 found = True
539 break
540 if found:
541 continue
542 rebuild_cache = True
543 if not opts.all_names and not check_dns_name(c):
544 continue
545 delete_list.append(c)
547 if len(delete_list) == 0 and len(update_list) == 0 and not rebuild_cache:
548 if opts.verbose:
549 print "No DNS updates needed"
550 sys.exit(0)
552 # get our krb5 creds
553 if len(delete_list) != 0 or len(update_list) != 0:
554 if not opts.nocreds:
555 get_credentials(lp)
557 # ask nsupdate to delete entries as needed
558 for d in delete_list:
559 if am_rodc:
560 if d.name.lower() == domain.lower():
561 continue
562 if not d.type in [ 'A', 'AAAA' ]:
563 call_rodc_update(d, op="delete")
564 else:
565 call_nsupdate(d, op="delete")
566 else:
567 call_nsupdate(d, op="delete")
569 # ask nsupdate to add entries as needed
570 for d in update_list:
571 if am_rodc:
572 if d.name.lower() == domain.lower():
573 continue
574 if not d.type in [ 'A', 'AAAA' ]:
575 call_rodc_update(d)
576 else:
577 call_nsupdate(d)
578 else:
579 call_nsupdate(d)
581 if rebuild_cache:
582 (file_dir, file_name) = os.path.split(dns_update_cache)
583 (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
584 wfile = os.fdopen(tmp_fd, 'a')
585 for d in dns_list:
586 wfile.write(str(d)+"\n")
587 os.rename(tmpfile, dns_update_cache)
588 fcntl.lockf(cfile, fcntl.LOCK_UN)
590 # delete the ccache if we created it
591 if ccachename is not None:
592 os.unlink(ccachename)
594 if error_count != 0:
595 print("Failed update of %u entries" % error_count)
596 sys.exit(error_count)