samba_dnsupdate: Mention contents of invalid line when encountering parsing error.
[Samba/wip.git] / source4 / scripting / bin / samba_dnsupdate
blobd21496ca219341217d9bd5a521ccb56b18a1e730
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")
69 creds = None
70 ccachename = None
72 opts, args = parser.parse_args()
74 if len(args) != 0:
75 parser.print_usage()
76 sys.exit(1)
78 lp = sambaopts.get_loadparm()
80 domain = lp.get("realm")
81 host = lp.get("netbios name")
82 if opts.all_interfaces:
83 all_interfaces = True
84 else:
85 all_interfaces = False
87 IPs = samba.interface_ips(lp, all_interfaces)
88 nsupdate_cmd = lp.get('nsupdate command')
90 if len(IPs) == 0:
91 print "No IP interfaces - skipping DNS updates"
92 sys.exit(0)
94 IP6s = []
95 IP4s = []
96 for i in IPs:
97 if i.find(':') != -1:
98 if i.find('%') == -1:
99 # we don't want link local addresses for DNS updates
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 creds.get_named_ccache(lp, ccachename)
123 class dnsobj(object):
124 """an object to hold a parsed DNS line"""
126 def __init__(self, string_form):
127 list = string_form.split()
128 if len(list) < 3:
129 raise Exception("Invalid DNS entry %r" % string_form)
130 self.dest = None
131 self.port = None
132 self.ip = None
133 self.existing_port = None
134 self.existing_weight = None
135 self.type = list[0]
136 self.name = list[1].lower()
137 if self.type == 'SRV':
138 if len(list) < 4:
139 raise Exception("Invalid DNS entry %r" % string_form)
140 self.dest = list[2].lower()
141 self.port = list[3]
142 elif self.type in ['A', 'AAAA']:
143 self.ip = list[2] # usually $IP, which gets replaced
144 elif self.type == 'CNAME':
145 self.dest = list[2].lower()
146 elif self.type == 'NS':
147 self.dest = list[2].lower()
148 else:
149 raise Exception("Received unexpected DNS reply of type %s" % self.type)
151 def __str__(self):
152 if d.type == "A": return "%s %s %s" % (self.type, self.name, self.ip)
153 if d.type == "AAAA": return "%s %s %s" % (self.type, self.name, self.ip)
154 if d.type == "SRV": return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
155 if d.type == "CNAME": return "%s %s %s" % (self.type, self.name, self.dest)
156 if d.type == "NS": return "%s %s %s" % (self.type, self.name, self.dest)
159 def parse_dns_line(line, sub_vars):
160 """parse a DNS line from."""
161 if line.startswith("SRV _ldap._tcp.pdc._msdcs.") and not samdb.am_pdc():
162 if opts.verbose:
163 print "Skipping PDC entry (%s) as we are not a PDC" % line
164 return None
165 subline = samba.substitute_var(line, sub_vars)
166 return dnsobj(subline)
169 def hostname_match(h1, h2):
170 """see if two hostnames match."""
171 h1 = str(h1)
172 h2 = str(h2)
173 return h1.lower().rstrip('.') == h2.lower().rstrip('.')
176 def check_dns_name(d):
177 """check that a DNS entry exists."""
178 normalised_name = d.name.rstrip('.') + '.'
179 if opts.verbose:
180 print "Looking for DNS entry %s as %s" % (d, normalised_name)
182 if opts.use_file is not None:
183 try:
184 dns_file = open(opts.use_file, "r")
185 except IOError:
186 return False
188 for line in dns_file:
189 line = line.strip()
190 if line == '' or line[0] == "#":
191 continue
192 if line.lower() == str(d).lower():
193 return True
194 return False
196 resolver = dns.resolver.Resolver()
197 if d.type == "NS":
198 # we need to lookup the nameserver for the parent domain,
199 # and use that to check the NS record
200 parent_domain = '.'.join(normalised_name.split('.')[1:])
201 try:
202 ans = resolver.query(parent_domain, 'NS')
203 except dns.exception.DNSException:
204 if opts.verbose:
205 print "Failed to find parent NS for %s" % d
206 return False
207 nameservers = set()
208 for i in range(len(ans)):
209 try:
210 ns = resolver.query(str(ans[i]), 'A')
211 except dns.exception.DNSException:
212 continue
213 for j in range(len(ns)):
214 nameservers.add(str(ns[j]))
215 d.nameservers = list(nameservers)
217 try:
218 if getattr(d, 'nameservers', None):
219 resolver.nameservers = list(d.nameservers)
220 ans = resolver.query(normalised_name, d.type)
221 except dns.exception.DNSException:
222 if opts.verbose:
223 print "Failed to find DNS entry %s" % d
224 return False
225 if d.type in ['A', 'AAAA']:
226 # we need to be sure that our IP is there
227 for rdata in ans:
228 if str(rdata) == str(d.ip):
229 return True
230 elif d.type == 'CNAME':
231 for i in range(len(ans)):
232 if hostname_match(ans[i].target, d.dest):
233 return True
234 elif d.type == 'NS':
235 for i in range(len(ans)):
236 if hostname_match(ans[i].target, d.dest):
237 return True
238 elif d.type == 'SRV':
239 for rdata in ans:
240 if opts.verbose:
241 print "Checking %s against %s" % (rdata, d)
242 if hostname_match(rdata.target, d.dest):
243 if str(rdata.port) == str(d.port):
244 return True
245 else:
246 d.existing_port = str(rdata.port)
247 d.existing_weight = str(rdata.weight)
249 if opts.verbose:
250 print "Failed to find matching DNS entry %s" % d
252 return False
255 def get_subst_vars(samdb):
256 """get the list of substitution vars."""
257 global lp, am_rodc
258 vars = {}
260 vars['DNSDOMAIN'] = samdb.domain_dns_name()
261 vars['DNSFOREST'] = samdb.forest_dns_name()
262 vars['HOSTNAME'] = samdb.host_dns_name()
263 vars['NTDSGUID'] = samdb.get_ntds_GUID()
264 vars['SITE'] = samdb.server_site_name()
265 res = samdb.search(base=samdb.get_default_basedn(), scope=SCOPE_BASE, attrs=["objectGUID"])
266 guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
267 vars['DOMAINGUID'] = guid
268 am_rodc = samdb.am_rodc()
270 return vars
273 def call_nsupdate(d):
274 """call nsupdate for an entry."""
275 global ccachename, nsupdate_cmd
277 if opts.verbose:
278 print "Calling nsupdate for %s" % d
280 if opts.use_file is not None:
281 wfile = open(opts.use_file, 'a')
282 fcntl.lockf(wfile, fcntl.LOCK_EX)
283 wfile.write(str(d)+"\n")
284 fcntl.lockf(wfile, fcntl.LOCK_UN)
285 return
287 normalised_name = d.name.rstrip('.') + '.'
289 (tmp_fd, tmpfile) = tempfile.mkstemp()
290 f = os.fdopen(tmp_fd, 'w')
291 if getattr(d, 'nameservers', None):
292 f.write('server %s\n' % d.nameservers[0])
293 if d.type == "A":
294 f.write("update add %s %u A %s\n" % (normalised_name, default_ttl, d.ip))
295 if d.type == "AAAA":
296 f.write("update add %s %u AAAA %s\n" % (normalised_name, default_ttl, d.ip))
297 if d.type == "SRV":
298 if d.existing_port is not None:
299 f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
300 d.existing_port, d.dest))
301 f.write("update add %s %u SRV 0 100 %s %s\n" % (normalised_name, default_ttl, d.port, d.dest))
302 if d.type == "CNAME":
303 f.write("update add %s %u CNAME %s\n" % (normalised_name, default_ttl, d.dest))
304 if d.type == "NS":
305 f.write("update add %s %u NS %s\n" % (normalised_name, default_ttl, d.dest))
306 if opts.verbose:
307 f.write("show\n")
308 f.write("send\n")
309 f.close()
311 global error_count
312 if ccachename:
313 os.environ["KRB5CCNAME"] = ccachename
314 try:
315 cmd = nsupdate_cmd[:]
316 cmd.append(tmpfile)
317 if ccachename:
318 env = {"KRB5CCNAME": ccachename}
319 else:
320 env = {}
321 ret = subprocess.call(cmd, shell=False, env=env)
322 if ret != 0:
323 if opts.fail_immediately:
324 if opts.verbose:
325 print("Failed update with %s" % tmpfile)
326 sys.exit(1)
327 error_count = error_count + 1
328 if opts.verbose:
329 print("Failed nsupdate: %d" % ret)
330 except Exception, estr:
331 if opts.fail_immediately:
332 sys.exit(1)
333 error_count = error_count + 1
334 if opts.verbose:
335 print("Failed nsupdate: %s : %s" % (str(d), estr))
336 os.unlink(tmpfile)
340 def rodc_dns_update(d, t):
341 '''a single DNS update via the RODC netlogon call'''
342 global sub_vars
344 if opts.verbose:
345 print "Calling netlogon RODC update for %s" % d
347 typemap = {
348 netlogon.NlDnsLdapAtSite : netlogon.NlDnsInfoTypeNone,
349 netlogon.NlDnsGcAtSite : netlogon.NlDnsDomainNameAlias,
350 netlogon.NlDnsDsaCname : netlogon.NlDnsDomainNameAlias,
351 netlogon.NlDnsKdcAtSite : netlogon.NlDnsInfoTypeNone,
352 netlogon.NlDnsDcAtSite : netlogon.NlDnsInfoTypeNone,
353 netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
354 netlogon.NlDnsGenericGcAtSite : netlogon.NlDnsDomainNameAlias
357 w = winbind.winbind("irpc:winbind_server", lp)
358 dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
359 dns_names.count = 1
360 name = netlogon.NL_DNS_NAME_INFO()
361 name.type = t
362 name.dns_domain_info_type = typemap[t]
363 name.priority = 0
364 name.weight = 0
365 if d.port is not None:
366 name.port = int(d.port)
367 name.dns_register = True
368 dns_names.names = [ name ]
369 site_name = sub_vars['SITE'].decode('utf-8')
371 global error_count
373 try:
374 ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
375 if ret_names.names[0].status != 0:
376 print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
377 error_count = error_count + 1
378 except RuntimeError, reason:
379 print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
380 error_count = error_count + 1
382 if error_count != 0 and opts.fail_immediately:
383 sys.exit(1)
386 def call_rodc_update(d):
387 '''RODCs need to use the netlogon API for nsupdate'''
388 global lp, sub_vars
390 # we expect failure for 3268 if we aren't a GC
391 if d.port is not None and int(d.port) == 3268:
392 return
394 # map the DNS request to a netlogon update type
395 map = {
396 netlogon.NlDnsLdapAtSite : '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
397 netlogon.NlDnsGcAtSite : '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
398 netlogon.NlDnsDsaCname : '${NTDSGUID}._msdcs.${DNSFOREST}',
399 netlogon.NlDnsKdcAtSite : '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
400 netlogon.NlDnsDcAtSite : '_ldap._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
401 netlogon.NlDnsRfc1510KdcAtSite : '_kerberos._tcp.${SITE}._sites.${DNSDOMAIN}',
402 netlogon.NlDnsGenericGcAtSite : '_gc._tcp.${SITE}._sites.${DNSFOREST}'
405 for t in map:
406 subname = samba.substitute_var(map[t], sub_vars)
407 if subname.lower() == d.name.lower():
408 # found a match - do the update
409 rodc_dns_update(d, t)
410 return
411 if opts.verbose:
412 print("Unable to map to netlogon DNS update: %s" % d)
415 # get the list of DNS entries we should have
416 if opts.update_list:
417 dns_update_list = opts.update_list
418 else:
419 dns_update_list = lp.private_path('dns_update_list')
421 # use our private krb5.conf to avoid problems with the wrong domain
422 # bind9 nsupdate wants the default domain set
423 krb5conf = lp.private_path('krb5.conf')
424 os.environ['KRB5_CONFIG'] = krb5conf
426 file = open(dns_update_list, "r")
428 samdb = SamDB(url=lp.samdb_url(), session_info=system_session(), lp=lp)
430 # get the substitution dictionary
431 sub_vars = get_subst_vars(samdb)
433 # build up a list of update commands to pass to nsupdate
434 update_list = []
435 dns_list = []
437 dup_set = set()
439 # read each line, and check that the DNS name exists
440 for line in file:
441 line = line.strip()
442 if line == '' or line[0] == "#":
443 continue
444 d = parse_dns_line(line, sub_vars)
445 if d is None:
446 continue
447 if d.type == 'A' and len(IP4s) == 0:
448 continue
449 if d.type == 'AAAA' and len(IP6s) == 0:
450 continue
451 if str(d) not in dup_set:
452 dns_list.append(d)
453 dup_set.add(str(d))
455 # now expand the entries, if any are A record with ip set to $IP
456 # then replace with multiple entries, one for each interface IP
457 for d in dns_list:
458 if d.ip != "$IP":
459 continue
460 if d.type == 'A':
461 d.ip = IP4s[0]
462 for i in range(len(IP4s)-1):
463 d2 = dnsobj(str(d))
464 d2.ip = IP4s[i+1]
465 dns_list.append(d2)
466 if d.type == 'AAAA':
467 d.ip = IP6s[0]
468 for i in range(len(IP6s)-1):
469 d2 = dnsobj(str(d))
470 d2.ip = IP6s[i+1]
471 dns_list.append(d2)
473 # now check if the entries already exist on the DNS server
474 for d in dns_list:
475 if opts.all_names or not check_dns_name(d):
476 update_list.append(d)
478 if len(update_list) == 0:
479 if opts.verbose:
480 print "No DNS updates needed"
481 sys.exit(0)
483 # get our krb5 creds
484 if not opts.nocreds:
485 get_credentials(lp)
487 # ask nsupdate to add entries as needed
488 for d in update_list:
489 if am_rodc:
490 if d.name.lower() == domain.lower():
491 continue
492 if not d.type in [ 'A', 'AAAA' ]:
493 call_rodc_update(d)
494 else:
495 call_nsupdate(d)
496 else:
497 call_nsupdate(d)
499 # delete the ccache if we created it
500 if ccachename is not None:
501 os.unlink(ccachename)
503 if error_count != 0:
504 print("Failed update of %u entries" % error_count)
505 sys.exit(error_count)