s3-selftest: introduce registry upgrade test
[Samba/gebeck_regimport.git] / source4 / scripting / bin / samba_dnsupdate
blobd6751b087684dc0b7a8a5a03e3e6812285789ad0
1 #!/usr/bin/env python
3 # update our DNS names using TSIG-GSS
5 # Copyright (C) Andrew Tridgell 2010
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 import os
22 import fcntl
23 import sys
24 import tempfile
25 import subprocess
27 # ensure we get messages out immediately, so they get in the samba logs,
28 # and don't get swallowed by a timeout
29 os.environ['PYTHONUNBUFFERED'] = '1'
31 # forcing GMT avoids a problem in some timezones with kerberos. Both MIT
32 # heimdal can get mutual authentication errors due to the 24 second difference
33 # between UTC and GMT when using some zone files (eg. the PDT zone from
34 # the US)
35 os.environ["TZ"] = "GMT"
37 # Find right directory when running from source tree
38 sys.path.insert(0, "bin/python")
40 import samba
41 import optparse
42 from samba import getopt as options
43 from ldb import SCOPE_BASE
44 from samba.auth import system_session
45 from samba.samdb import SamDB
46 from samba.dcerpc import netlogon, winbind
48 samba.ensure_external_module("dns", "dnspython")
49 import dns.resolver
50 import dns.exception
52 default_ttl = 900
53 am_rodc = False
54 error_count = 0
56 parser = optparse.OptionParser("samba_dnsupdate")
57 sambaopts = options.SambaOptions(parser)
58 parser.add_option_group(sambaopts)
59 parser.add_option_group(options.VersionOptions(parser))
60 parser.add_option("--verbose", action="store_true")
61 parser.add_option("--all-names", action="store_true")
62 parser.add_option("--all-interfaces", action="store_true")
63 parser.add_option("--use-file", type="string", help="Use a file, rather than real DNS calls")
64 parser.add_option("--update-list", type="string", help="Add DNS names from the given file")
65 parser.add_option("--fail-immediately", action='store_true', help="Exit on first failure")
67 creds = None
68 ccachename = None
70 opts, args = parser.parse_args()
72 if len(args) != 0:
73 parser.print_usage()
74 sys.exit(1)
76 lp = sambaopts.get_loadparm()
78 domain = lp.get("realm")
79 host = lp.get("netbios name")
80 if opts.all_interfaces:
81 all_interfaces = True
82 else:
83 all_interfaces = False
85 IPs = samba.interface_ips(lp, all_interfaces)
86 nsupdate_cmd = lp.get('nsupdate command')
88 if len(IPs) == 0:
89 print "No IP interfaces - skipping DNS updates"
90 sys.exit(0)
92 IP6s = []
93 IP4s = []
94 for i in IPs:
95 if i.find(':') != -1:
96 if i.find('%') == -1:
97 # we don't want link local addresses for DNS updates
98 IP6s.append(i)
99 else:
100 IP4s.append(i)
103 if opts.verbose:
104 print "IPs: %s" % IPs
106 ########################################################
107 # get credentials if we haven't got them already
108 def get_credentials(lp):
109 from samba import credentials
110 global ccachename, creds
111 if creds is not None:
112 return
113 creds = credentials.Credentials()
114 creds.guess(lp)
115 creds.set_machine_account(lp)
116 creds.set_krb_forwardable(credentials.NO_KRB_FORWARDABLE)
117 (tmp_fd, ccachename) = tempfile.mkstemp()
118 creds.get_named_ccache(lp, ccachename)
121 #############################################
122 # an object to hold a parsed DNS line
123 class dnsobj(object):
124 def __init__(self, string_form):
125 list = string_form.split()
126 self.dest = None
127 self.port = None
128 self.ip = None
129 self.existing_port = None
130 self.existing_weight = None
131 self.type = list[0]
132 self.name = list[1].lower()
133 if self.type == 'SRV':
134 self.dest = list[2].lower()
135 self.port = list[3]
136 elif self.type in ['A', 'AAAA']:
137 self.ip = list[2] # usually $IP, which gets replaced
138 elif self.type == 'CNAME':
139 self.dest = list[2].lower()
140 elif self.type == 'NS':
141 self.dest = list[2].lower()
142 else:
143 print "Received unexpected DNS reply of type %s" % self.type
144 raise
146 def __str__(self):
147 if d.type == "A": return "%s %s %s" % (self.type, self.name, self.ip)
148 if d.type == "AAAA": return "%s %s %s" % (self.type, self.name, self.ip)
149 if d.type == "SRV": return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
150 if d.type == "CNAME": return "%s %s %s" % (self.type, self.name, self.dest)
151 if d.type == "NS": return "%s %s %s" % (self.type, self.name, self.dest)
154 ################################################
155 # parse a DNS line from
156 def parse_dns_line(line, sub_vars):
157 subline = samba.substitute_var(line, sub_vars)
158 d = dnsobj(subline)
159 return d
161 ############################################
162 # see if two hostnames match
163 def hostname_match(h1, h2):
164 h1 = str(h1)
165 h2 = str(h2)
166 return h1.lower().rstrip('.') == h2.lower().rstrip('.')
169 ############################################
170 # check that a DNS entry exists
171 def check_dns_name(d):
172 normalised_name = d.name.rstrip('.') + '.'
173 if opts.verbose:
174 print "Looking for DNS entry %s as %s" % (d, normalised_name)
176 if opts.use_file is not None:
177 try:
178 dns_file = open(opts.use_file, "r")
179 except IOError:
180 return False
182 for line in dns_file:
183 line = line.strip()
184 if line == '' or line[0] == "#":
185 continue
186 if line.lower() == str(d).lower():
187 return True
188 return False
190 resolver = dns.resolver.Resolver()
191 if d.type == "NS":
192 # we need to lookup the nameserver for the parent domain,
193 # and use that to check the NS record
194 parent_domain = '.'.join(normalised_name.split('.')[1:])
195 try:
196 ans = resolver.query(parent_domain, 'NS')
197 except dns.exception.DNSException:
198 if opts.verbose:
199 print "Failed to find parent NS for %s" % d
200 return False
201 nameservers = set()
202 for i in range(len(ans)):
203 try:
204 ns = resolver.query(str(ans[i]), 'A')
205 except dns.exception.DNSException:
206 continue
207 for j in range(len(ns)):
208 nameservers.add(str(ns[j]))
209 d.nameservers = list(nameservers)
211 try:
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:
216 if opts.verbose:
217 print "Failed to find DNS entry %s" % d
218 return False
219 if d.type in ['A', 'AAAA']:
220 # we need to be sure that our IP is there
221 for rdata in ans:
222 if str(rdata) == str(d.ip):
223 return True
224 if d.type == 'CNAME':
225 for i in range(len(ans)):
226 if hostname_match(ans[i].target, d.dest):
227 return True
228 if d.type == 'NS':
229 for i in range(len(ans)):
230 if hostname_match(ans[i].target, d.dest):
231 return True
232 if d.type == 'SRV':
233 for rdata in ans:
234 if opts.verbose:
235 print "Checking %s against %s" % (rdata, d)
236 if hostname_match(rdata.target, d.dest):
237 if str(rdata.port) == str(d.port):
238 return True
239 else:
240 d.existing_port = str(rdata.port)
241 d.existing_weight = str(rdata.weight)
243 if opts.verbose:
244 print "Failed to find matching DNS entry %s" % d
246 return False
249 ###########################################
250 # get the list of substitution vars
251 def get_subst_vars():
252 global lp, am_rodc
253 vars = {}
255 samdb = SamDB(url=lp.samdb_url(), session_info=system_session(),
256 lp=lp)
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
266 am_rodc = samdb.am_rodc()
268 return vars
271 ############################################
272 # call nsupdate for an entry
273 def call_nsupdate(d):
274 global ccachename, nsupdate_cmd
276 if opts.verbose:
277 print "Calling nsupdate for %s" % d
279 if opts.use_file is not None:
280 wfile = open(opts.use_file, 'a')
281 fcntl.lockf(wfile, fcntl.LOCK_EX)
282 wfile.write(str(d)+"\n")
283 fcntl.lockf(wfile, fcntl.LOCK_UN)
284 return
286 normalised_name = d.name.rstrip('.') + '.'
288 (tmp_fd, tmpfile) = tempfile.mkstemp()
289 f = os.fdopen(tmp_fd, 'w')
290 if getattr(d, 'nameservers', None):
291 f.write('server %s\n' % d.nameservers[0])
292 if d.type == "A":
293 f.write("update add %s %u A %s\n" % (normalised_name, default_ttl, d.ip))
294 if d.type == "AAAA":
295 f.write("update add %s %u AAAA %s\n" % (normalised_name, default_ttl, d.ip))
296 if d.type == "SRV":
297 if d.existing_port is not None:
298 f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
299 d.existing_port, d.dest))
300 f.write("update add %s %u SRV 0 100 %s %s\n" % (normalised_name, default_ttl, d.port, d.dest))
301 if d.type == "CNAME":
302 f.write("update add %s %u CNAME %s\n" % (normalised_name, default_ttl, d.dest))
303 if d.type == "NS":
304 f.write("update add %s %u NS %s\n" % (normalised_name, default_ttl, d.dest))
305 if opts.verbose:
306 f.write("show\n")
307 f.write("send\n")
308 f.close()
310 global error_count
311 os.environ["KRB5CCNAME"] = ccachename
312 try:
313 cmd = nsupdate_cmd[:]
314 cmd.append(tmpfile)
315 ret = subprocess.call(cmd, shell=False, env={"KRB5CCNAME": ccachename})
316 if ret != 0:
317 if opts.fail_immediately:
318 if opts.verbose:
319 print("Failed update with %s" % tmpfile)
320 sys.exit(1)
321 error_count = error_count + 1
322 if opts.verbose:
323 print("Failed nsupdate: %d" % ret)
324 except Exception, estr:
325 if opts.fail_immediately:
326 sys.exit(1)
327 error_count = error_count + 1
328 if opts.verbose:
329 print("Failed nsupdate: %s : %s" % (str(d), estr))
330 os.unlink(tmpfile)
334 def rodc_dns_update(d, t):
335 '''a single DNS update via the RODC netlogon call'''
336 global sub_vars
338 if opts.verbose:
339 print "Calling netlogon RODC update for %s" % d
341 typemap = {
342 netlogon.NlDnsLdapAtSite : netlogon.NlDnsInfoTypeNone,
343 netlogon.NlDnsGcAtSite : netlogon.NlDnsDomainNameAlias,
344 netlogon.NlDnsDsaCname : netlogon.NlDnsDomainNameAlias,
345 netlogon.NlDnsKdcAtSite : netlogon.NlDnsInfoTypeNone,
346 netlogon.NlDnsDcAtSite : netlogon.NlDnsInfoTypeNone,
347 netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
348 netlogon.NlDnsGenericGcAtSite : netlogon.NlDnsDomainNameAlias
351 w = winbind.winbind("irpc:winbind_server", lp)
352 dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
353 dns_names.count = 1
354 name = netlogon.NL_DNS_NAME_INFO()
355 name.type = t
356 name.dns_domain_info_type = typemap[t]
357 name.priority = 0
358 name.weight = 0
359 if d.port is not None:
360 name.port = int(d.port)
361 name.dns_register = True
362 dns_names.names = [ name ]
363 site_name = sub_vars['SITE'].decode('utf-8')
365 global error_count
367 try:
368 ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
369 if ret_names.names[0].status != 0:
370 print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
371 error_count = error_count + 1
372 except RuntimeError, reason:
373 print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
374 error_count = error_count + 1
376 if error_count != 0 and opts.fail_immediately:
377 sys.exit(1)
380 def call_rodc_update(d):
381 '''RODCs need to use the netlogon API for nsupdate'''
382 global lp, sub_vars
384 # we expect failure for 3268 if we aren't a GC
385 if d.port is not None and int(d.port) == 3268:
386 return
388 # map the DNS request to a netlogon update type
389 map = {
390 netlogon.NlDnsLdapAtSite : '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
391 netlogon.NlDnsGcAtSite : '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
392 netlogon.NlDnsDsaCname : '${NTDSGUID}._msdcs.${DNSFOREST}',
393 netlogon.NlDnsKdcAtSite : '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
394 netlogon.NlDnsDcAtSite : '_ldap._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
395 netlogon.NlDnsRfc1510KdcAtSite : '_kerberos._tcp.${SITE}._sites.${DNSDOMAIN}',
396 netlogon.NlDnsGenericGcAtSite : '_gc._tcp.${SITE}._sites.${DNSFOREST}'
399 for t in map:
400 subname = samba.substitute_var(map[t], sub_vars)
401 if subname.lower() == d.name.lower():
402 # found a match - do the update
403 rodc_dns_update(d, t)
404 return
405 if opts.verbose:
406 print("Unable to map to netlogon DNS update: %s" % d)
409 # get the list of DNS entries we should have
410 if opts.update_list:
411 dns_update_list = opts.update_list
412 else:
413 dns_update_list = lp.private_path('dns_update_list')
415 # use our private krb5.conf to avoid problems with the wrong domain
416 # bind9 nsupdate wants the default domain set
417 krb5conf = lp.private_path('krb5.conf')
418 os.environ['KRB5_CONFIG'] = krb5conf
420 file = open(dns_update_list, "r")
422 # get the substitution dictionary
423 sub_vars = get_subst_vars()
425 # build up a list of update commands to pass to nsupdate
426 update_list = []
427 dns_list = []
429 dup_set = set()
431 # read each line, and check that the DNS name exists
432 for line in file:
433 line = line.strip()
434 if line == '' or line[0] == "#":
435 continue
436 d = parse_dns_line(line, sub_vars)
437 if d.type == 'A' and len(IP4s) == 0:
438 continue
439 if d.type == 'AAAA' and len(IP6s) == 0:
440 continue
441 if str(d) not in dup_set:
442 dns_list.append(d)
443 dup_set.add(str(d))
445 # now expand the entries, if any are A record with ip set to $IP
446 # then replace with multiple entries, one for each interface IP
447 for d in dns_list:
448 if d.ip != "$IP":
449 continue
450 if d.type == 'A':
451 d.ip = IP4s[0]
452 for i in range(len(IP4s)-1):
453 d2 = dnsobj(str(d))
454 d2.ip = IP4s[i+1]
455 dns_list.append(d2)
456 if d.type == 'AAAA':
457 d.ip = IP6s[0]
458 for i in range(len(IP6s)-1):
459 d2 = dnsobj(str(d))
460 d2.ip = IP6s[i+1]
461 dns_list.append(d2)
463 # now check if the entries already exist on the DNS server
464 for d in dns_list:
465 if opts.all_names or not check_dns_name(d):
466 update_list.append(d)
468 if len(update_list) == 0:
469 if opts.verbose:
470 print "No DNS updates needed"
471 sys.exit(0)
473 # get our krb5 creds
474 get_credentials(lp)
476 # ask nsupdate to add entries as needed
477 for d in update_list:
478 if am_rodc:
479 if d.name.lower() == domain.lower():
480 continue
481 if not d.type in [ 'A', 'AAAA' ]:
482 call_rodc_update(d)
483 else:
484 call_nsupdate(d)
485 else:
486 call_nsupdate(d)
488 # delete the ccache if we created it
489 if ccachename is not None:
490 os.unlink(ccachename)
492 if error_count != 0:
493 print("Failed update of %u entries" % error_count)
494 sys.exit(error_count)