scripting: Move get_diff_sds from samba.upgradehelpers to samba.descriptor
[Samba/gbeck.git] / source4 / scripting / bin / samba_dnsupdate
blob33c16ecd00f4f9ff0a4ea819ff728ea26a13a611
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("--fail-immediately", action='store_true', help="Exit on first failure")
67 parser.add_option("--no-credentials", dest='nocreds', action='store_true', help="don't try and get credentials")
68 parser.add_option("--no-substiutions", dest='nosubs', action='store_true', help="don't try and expands variables in file specified by --update-list")
70 creds = None
71 ccachename = None
73 opts, args = parser.parse_args()
75 if len(args) != 0:
76 parser.print_usage()
77 sys.exit(1)
79 lp = sambaopts.get_loadparm()
81 domain = lp.get("realm")
82 host = lp.get("netbios name")
83 if opts.all_interfaces:
84 all_interfaces = True
85 else:
86 all_interfaces = False
88 IPs = samba.interface_ips(lp, all_interfaces)
89 nsupdate_cmd = lp.get('nsupdate command')
91 if len(IPs) == 0:
92 print "No IP interfaces - skipping DNS updates"
93 sys.exit(0)
95 IP6s = []
96 IP4s = []
97 for i in IPs:
98 if i.find(':') != -1:
99 IP6s.append(i)
100 else:
101 IP4s.append(i)
104 if opts.verbose:
105 print "IPs: %s" % IPs
108 def get_credentials(lp):
109 """# get credentials if we haven't got them already."""
110 from samba import credentials
111 global ccachename, creds
112 if creds is not None:
113 return
114 creds = credentials.Credentials()
115 creds.guess(lp)
116 creds.set_machine_account(lp)
117 creds.set_krb_forwardable(credentials.NO_KRB_FORWARDABLE)
118 (tmp_fd, ccachename) = tempfile.mkstemp()
119 creds.get_named_ccache(lp, ccachename)
122 class dnsobj(object):
123 """an object to hold a parsed DNS line"""
125 def __init__(self, string_form):
126 list = string_form.split()
127 if len(list) < 3:
128 raise Exception("Invalid DNS entry %r" % string_form)
129 self.dest = None
130 self.port = None
131 self.ip = None
132 self.existing_port = None
133 self.existing_weight = None
134 self.type = list[0]
135 self.name = list[1].lower()
136 if self.type == 'SRV':
137 if len(list) < 4:
138 raise Exception("Invalid DNS entry %r" % string_form)
139 self.dest = list[2].lower()
140 self.port = list[3]
141 elif self.type in ['A', 'AAAA']:
142 self.ip = list[2] # usually $IP, which gets replaced
143 elif self.type == 'CNAME':
144 self.dest = list[2].lower()
145 elif self.type == 'NS':
146 self.dest = list[2].lower()
147 else:
148 raise Exception("Received unexpected DNS reply of type %s" % self.type)
150 def __str__(self):
151 if d.type == "A":
152 return "%s %s %s" % (self.type, self.name, self.ip)
153 if d.type == "AAAA":
154 return "%s %s %s" % (self.type, self.name, self.ip)
155 if d.type == "SRV":
156 return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
157 if d.type == "CNAME":
158 return "%s %s %s" % (self.type, self.name, self.dest)
159 if d.type == "NS":
160 return "%s %s %s" % (self.type, self.name, self.dest)
163 def parse_dns_line(line, sub_vars):
164 """parse a DNS line from."""
165 if line.startswith("SRV _ldap._tcp.pdc._msdcs.") and not samdb.am_pdc():
166 if opts.verbose:
167 print "Skipping PDC entry (%s) as we are not a PDC" % line
168 return None
169 subline = samba.substitute_var(line, sub_vars)
170 return dnsobj(subline)
173 def hostname_match(h1, h2):
174 """see if two hostnames match."""
175 h1 = str(h1)
176 h2 = str(h2)
177 return h1.lower().rstrip('.') == h2.lower().rstrip('.')
180 def check_dns_name(d):
181 """check that a DNS entry exists."""
182 normalised_name = d.name.rstrip('.') + '.'
183 if opts.verbose:
184 print "Looking for DNS entry %s as %s" % (d, normalised_name)
186 if opts.use_file is not None:
187 try:
188 dns_file = open(opts.use_file, "r")
189 except IOError:
190 return False
192 for line in dns_file:
193 line = line.strip()
194 if line == '' or line[0] == "#":
195 continue
196 if line.lower() == str(d).lower():
197 return True
198 return False
200 resolver = dns.resolver.Resolver()
201 if d.type == "NS":
202 # we need to lookup the nameserver for the parent domain,
203 # and use that to check the NS record
204 parent_domain = '.'.join(normalised_name.split('.')[1:])
205 try:
206 ans = resolver.query(parent_domain, 'NS')
207 except dns.exception.DNSException:
208 if opts.verbose:
209 print "Failed to find parent NS for %s" % d
210 return False
211 nameservers = set()
212 for i in range(len(ans)):
213 try:
214 ns = resolver.query(str(ans[i]), 'A')
215 except dns.exception.DNSException:
216 continue
217 for j in range(len(ns)):
218 nameservers.add(str(ns[j]))
219 d.nameservers = list(nameservers)
221 try:
222 if getattr(d, 'nameservers', None):
223 resolver.nameservers = list(d.nameservers)
224 ans = resolver.query(normalised_name, d.type)
225 except dns.exception.DNSException:
226 if opts.verbose:
227 print "Failed to find DNS entry %s" % d
228 return False
229 if d.type in ['A', 'AAAA']:
230 # we need to be sure that our IP is there
231 for rdata in ans:
232 if str(rdata) == str(d.ip):
233 return True
234 elif d.type == 'CNAME':
235 for i in range(len(ans)):
236 if hostname_match(ans[i].target, d.dest):
237 return True
238 elif d.type == 'NS':
239 for i in range(len(ans)):
240 if hostname_match(ans[i].target, d.dest):
241 return True
242 elif d.type == 'SRV':
243 for rdata in ans:
244 if opts.verbose:
245 print "Checking %s against %s" % (rdata, d)
246 if hostname_match(rdata.target, d.dest):
247 if str(rdata.port) == str(d.port):
248 return True
249 else:
250 d.existing_port = str(rdata.port)
251 d.existing_weight = str(rdata.weight)
253 if opts.verbose:
254 print "Failed to find matching DNS entry %s" % d
256 return False
259 def get_subst_vars(samdb):
260 """get the list of substitution vars."""
261 global lp, am_rodc
262 vars = {}
264 vars['DNSDOMAIN'] = samdb.domain_dns_name()
265 vars['DNSFOREST'] = samdb.forest_dns_name()
266 vars['HOSTNAME'] = samdb.host_dns_name()
267 vars['NTDSGUID'] = samdb.get_ntds_GUID()
268 vars['SITE'] = samdb.server_site_name()
269 res = samdb.search(base=samdb.get_default_basedn(), scope=SCOPE_BASE, attrs=["objectGUID"])
270 guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
271 vars['DOMAINGUID'] = guid
272 am_rodc = samdb.am_rodc()
274 return vars
277 def call_nsupdate(d):
278 """call nsupdate for an entry."""
279 global ccachename, nsupdate_cmd, krb5conf
281 if opts.verbose:
282 print "Calling nsupdate for %s" % d
284 if opts.use_file is not None:
285 try:
286 rfile = open(opts.use_file, 'r+')
287 except IOError:
288 # Perhaps create it
289 rfile = open(opts.use_file, 'w+')
290 # Open it for reading again, in case someone else got to it first
291 rfile = open(opts.use_file, 'r+')
292 fcntl.lockf(rfile, fcntl.LOCK_EX)
293 (file_dir, file_name) = os.path.split(opts.use_file)
294 (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
295 wfile = os.fdopen(tmp_fd, 'a')
296 rfile.seek(0)
297 for line in rfile:
298 wfile.write(line)
299 wfile.write(str(d)+"\n")
300 os.rename(tmpfile, opts.use_file)
301 fcntl.lockf(rfile, fcntl.LOCK_UN)
302 return
304 normalised_name = d.name.rstrip('.') + '.'
306 (tmp_fd, tmpfile) = tempfile.mkstemp()
307 f = os.fdopen(tmp_fd, 'w')
308 if getattr(d, 'nameservers', None):
309 f.write('server %s\n' % d.nameservers[0])
310 if d.type == "A":
311 f.write("update add %s %u A %s\n" % (normalised_name, default_ttl, d.ip))
312 if d.type == "AAAA":
313 f.write("update add %s %u AAAA %s\n" % (normalised_name, default_ttl, d.ip))
314 if d.type == "SRV":
315 if d.existing_port is not None:
316 f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
317 d.existing_port, d.dest))
318 f.write("update add %s %u SRV 0 100 %s %s\n" % (normalised_name, default_ttl, d.port, d.dest))
319 if d.type == "CNAME":
320 f.write("update add %s %u CNAME %s\n" % (normalised_name, default_ttl, d.dest))
321 if d.type == "NS":
322 f.write("update add %s %u NS %s\n" % (normalised_name, default_ttl, d.dest))
323 if opts.verbose:
324 f.write("show\n")
325 f.write("send\n")
326 f.close()
328 global error_count
329 if ccachename:
330 os.environ["KRB5CCNAME"] = ccachename
331 try:
332 cmd = nsupdate_cmd[:]
333 cmd.append(tmpfile)
334 env = {}
335 if krb5conf:
336 env["KRB5_CONFIG"] = krb5conf
337 if ccachename:
338 env["KRB5CCNAME"] = ccachename
339 ret = subprocess.call(cmd, shell=False, env=env)
340 if ret != 0:
341 if opts.fail_immediately:
342 if opts.verbose:
343 print("Failed update with %s" % tmpfile)
344 sys.exit(1)
345 error_count = error_count + 1
346 if opts.verbose:
347 print("Failed nsupdate: %d" % ret)
348 except Exception, estr:
349 if opts.fail_immediately:
350 sys.exit(1)
351 error_count = error_count + 1
352 if opts.verbose:
353 print("Failed nsupdate: %s : %s" % (str(d), estr))
354 os.unlink(tmpfile)
358 def rodc_dns_update(d, t):
359 '''a single DNS update via the RODC netlogon call'''
360 global sub_vars
362 if opts.verbose:
363 print "Calling netlogon RODC update for %s" % d
365 typemap = {
366 netlogon.NlDnsLdapAtSite : netlogon.NlDnsInfoTypeNone,
367 netlogon.NlDnsGcAtSite : netlogon.NlDnsDomainNameAlias,
368 netlogon.NlDnsDsaCname : netlogon.NlDnsDomainNameAlias,
369 netlogon.NlDnsKdcAtSite : netlogon.NlDnsInfoTypeNone,
370 netlogon.NlDnsDcAtSite : netlogon.NlDnsInfoTypeNone,
371 netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
372 netlogon.NlDnsGenericGcAtSite : netlogon.NlDnsDomainNameAlias
375 w = winbind.winbind("irpc:winbind_server", lp)
376 dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
377 dns_names.count = 1
378 name = netlogon.NL_DNS_NAME_INFO()
379 name.type = t
380 name.dns_domain_info_type = typemap[t]
381 name.priority = 0
382 name.weight = 0
383 if d.port is not None:
384 name.port = int(d.port)
385 name.dns_register = True
386 dns_names.names = [ name ]
387 site_name = sub_vars['SITE'].decode('utf-8')
389 global error_count
391 try:
392 ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
393 if ret_names.names[0].status != 0:
394 print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
395 error_count = error_count + 1
396 except RuntimeError, reason:
397 print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
398 error_count = error_count + 1
400 if error_count != 0 and opts.fail_immediately:
401 sys.exit(1)
404 def call_rodc_update(d):
405 '''RODCs need to use the netlogon API for nsupdate'''
406 global lp, sub_vars
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)
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 # use our private krb5.conf to avoid problems with the wrong domain
440 # bind9 nsupdate wants the default domain set
441 krb5conf = lp.private_path('krb5.conf')
442 os.environ['KRB5_CONFIG'] = krb5conf
444 file = open(dns_update_list, "r")
446 if opts.nosubs:
447 sub_vars = {}
448 else:
449 samdb = SamDB(url=lp.samdb_url(), session_info=system_session(), lp=lp)
451 # get the substitution dictionary
452 sub_vars = get_subst_vars(samdb)
454 # build up a list of update commands to pass to nsupdate
455 update_list = []
456 dns_list = []
458 dup_set = set()
460 # read each line, and check that the DNS name exists
461 for line in file:
462 line = line.strip()
463 if line == '' or line[0] == "#":
464 continue
465 d = parse_dns_line(line, sub_vars)
466 if d is None:
467 continue
468 if d.type == 'A' and len(IP4s) == 0:
469 continue
470 if d.type == 'AAAA' and len(IP6s) == 0:
471 continue
472 if str(d) not in dup_set:
473 dns_list.append(d)
474 dup_set.add(str(d))
476 # now expand the entries, if any are A record with ip set to $IP
477 # then replace with multiple entries, one for each interface IP
478 for d in dns_list:
479 if d.ip != "$IP":
480 continue
481 if d.type == 'A':
482 d.ip = IP4s[0]
483 for i in range(len(IP4s)-1):
484 d2 = dnsobj(str(d))
485 d2.ip = IP4s[i+1]
486 dns_list.append(d2)
487 if d.type == 'AAAA':
488 d.ip = IP6s[0]
489 for i in range(len(IP6s)-1):
490 d2 = dnsobj(str(d))
491 d2.ip = IP6s[i+1]
492 dns_list.append(d2)
494 # now check if the entries already exist on the DNS server
495 for d in dns_list:
496 if opts.all_names or not check_dns_name(d):
497 update_list.append(d)
499 if len(update_list) == 0:
500 if opts.verbose:
501 print "No DNS updates needed"
502 sys.exit(0)
504 # get our krb5 creds
505 if not opts.nocreds:
506 get_credentials(lp)
508 # ask nsupdate to add entries as needed
509 for d in update_list:
510 if am_rodc:
511 if d.name.lower() == domain.lower():
512 continue
513 if not d.type in [ 'A', 'AAAA' ]:
514 call_rodc_update(d)
515 else:
516 call_nsupdate(d)
517 else:
518 call_nsupdate(d)
520 # delete the ccache if we created it
521 if ccachename is not None:
522 os.unlink(ccachename)
524 if error_count != 0:
525 print("Failed update of %u entries" % error_count)
526 sys.exit(error_count)