pysmbd: Add SMB_ACL_EXECUTE to the mask set by make_simple_acl()
[Samba/gebeck_regimport.git] / source4 / scripting / bin / samba_dnsupdate
bloba700118da0e6cf13a90b144f0d5e7f7edd36864a
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 if i.find('%') == -1:
100 # we don't want link local addresses for DNS updates
101 IP6s.append(i)
102 else:
103 IP4s.append(i)
106 if opts.verbose:
107 print "IPs: %s" % IPs
110 def get_credentials(lp):
111 """# get credentials if we haven't got them already."""
112 from samba import credentials
113 global ccachename, creds
114 if creds is not None:
115 return
116 creds = credentials.Credentials()
117 creds.guess(lp)
118 creds.set_machine_account(lp)
119 creds.set_krb_forwardable(credentials.NO_KRB_FORWARDABLE)
120 (tmp_fd, ccachename) = tempfile.mkstemp()
121 creds.get_named_ccache(lp, ccachename)
124 class dnsobj(object):
125 """an object to hold a parsed DNS line"""
127 def __init__(self, string_form):
128 list = string_form.split()
129 if len(list) < 3:
130 raise Exception("Invalid DNS entry %r" % string_form)
131 self.dest = None
132 self.port = None
133 self.ip = None
134 self.existing_port = None
135 self.existing_weight = None
136 self.type = list[0]
137 self.name = list[1].lower()
138 if self.type == 'SRV':
139 if len(list) < 4:
140 raise Exception("Invalid DNS entry %r" % string_form)
141 self.dest = list[2].lower()
142 self.port = list[3]
143 elif self.type in ['A', 'AAAA']:
144 self.ip = list[2] # usually $IP, which gets replaced
145 elif self.type == 'CNAME':
146 self.dest = list[2].lower()
147 elif self.type == 'NS':
148 self.dest = list[2].lower()
149 else:
150 raise Exception("Received unexpected DNS reply of type %s" % self.type)
152 def __str__(self):
153 if d.type == "A":
154 return "%s %s %s" % (self.type, self.name, self.ip)
155 if d.type == "AAAA":
156 return "%s %s %s" % (self.type, self.name, self.ip)
157 if d.type == "SRV":
158 return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
159 if d.type == "CNAME":
160 return "%s %s %s" % (self.type, self.name, self.dest)
161 if d.type == "NS":
162 return "%s %s %s" % (self.type, self.name, self.dest)
165 def parse_dns_line(line, sub_vars):
166 """parse a DNS line from."""
167 if line.startswith("SRV _ldap._tcp.pdc._msdcs.") and not samdb.am_pdc():
168 if opts.verbose:
169 print "Skipping PDC entry (%s) as we are not a PDC" % line
170 return None
171 subline = samba.substitute_var(line, sub_vars)
172 return dnsobj(subline)
175 def hostname_match(h1, h2):
176 """see if two hostnames match."""
177 h1 = str(h1)
178 h2 = str(h2)
179 return h1.lower().rstrip('.') == h2.lower().rstrip('.')
182 def check_dns_name(d):
183 """check that a DNS entry exists."""
184 normalised_name = d.name.rstrip('.') + '.'
185 if opts.verbose:
186 print "Looking for DNS entry %s as %s" % (d, normalised_name)
188 if opts.use_file is not None:
189 try:
190 dns_file = open(opts.use_file, "r")
191 except IOError:
192 return False
194 for line in dns_file:
195 line = line.strip()
196 if line == '' or line[0] == "#":
197 continue
198 if line.lower() == str(d).lower():
199 return True
200 return False
202 resolver = dns.resolver.Resolver()
203 if d.type == "NS":
204 # we need to lookup the nameserver for the parent domain,
205 # and use that to check the NS record
206 parent_domain = '.'.join(normalised_name.split('.')[1:])
207 try:
208 ans = resolver.query(parent_domain, 'NS')
209 except dns.exception.DNSException:
210 if opts.verbose:
211 print "Failed to find parent NS for %s" % d
212 return False
213 nameservers = set()
214 for i in range(len(ans)):
215 try:
216 ns = resolver.query(str(ans[i]), 'A')
217 except dns.exception.DNSException:
218 continue
219 for j in range(len(ns)):
220 nameservers.add(str(ns[j]))
221 d.nameservers = list(nameservers)
223 try:
224 if getattr(d, 'nameservers', None):
225 resolver.nameservers = list(d.nameservers)
226 ans = resolver.query(normalised_name, d.type)
227 except dns.exception.DNSException:
228 if opts.verbose:
229 print "Failed to find DNS entry %s" % d
230 return False
231 if d.type in ['A', 'AAAA']:
232 # we need to be sure that our IP is there
233 for rdata in ans:
234 if str(rdata) == str(d.ip):
235 return True
236 elif d.type == 'CNAME':
237 for i in range(len(ans)):
238 if hostname_match(ans[i].target, d.dest):
239 return True
240 elif d.type == 'NS':
241 for i in range(len(ans)):
242 if hostname_match(ans[i].target, d.dest):
243 return True
244 elif d.type == 'SRV':
245 for rdata in ans:
246 if opts.verbose:
247 print "Checking %s against %s" % (rdata, d)
248 if hostname_match(rdata.target, d.dest):
249 if str(rdata.port) == str(d.port):
250 return True
251 else:
252 d.existing_port = str(rdata.port)
253 d.existing_weight = str(rdata.weight)
255 if opts.verbose:
256 print "Failed to find matching DNS entry %s" % d
258 return False
261 def get_subst_vars(samdb):
262 """get the list of substitution vars."""
263 global lp, am_rodc
264 vars = {}
266 vars['DNSDOMAIN'] = samdb.domain_dns_name()
267 vars['DNSFOREST'] = samdb.forest_dns_name()
268 vars['HOSTNAME'] = samdb.host_dns_name()
269 vars['NTDSGUID'] = samdb.get_ntds_GUID()
270 vars['SITE'] = samdb.server_site_name()
271 res = samdb.search(base=samdb.get_default_basedn(), scope=SCOPE_BASE, attrs=["objectGUID"])
272 guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
273 vars['DOMAINGUID'] = guid
274 am_rodc = samdb.am_rodc()
276 return vars
279 def call_nsupdate(d):
280 """call nsupdate for an entry."""
281 global ccachename, nsupdate_cmd
283 if opts.verbose:
284 print "Calling nsupdate for %s" % d
286 if opts.use_file is not None:
287 try:
288 rfile = open(opts.use_file, 'r+')
289 except IOError:
290 # Perhaps create it
291 rfile = open(opts.use_file, 'w+')
292 # Open it for reading again, in case someone else got to it first
293 rfile = open(opts.use_file, 'r+')
294 fcntl.lockf(rfile, fcntl.LOCK_EX)
295 (file_dir, file_name) = os.path.split(opts.use_file)
296 (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
297 wfile = os.fdopen(tmp_fd, 'a')
298 rfile.seek(0)
299 for line in rfile:
300 wfile.write(line)
301 wfile.write(str(d)+"\n")
302 os.rename(tmpfile, opts.use_file)
303 fcntl.lockf(rfile, fcntl.LOCK_UN)
304 return
306 normalised_name = d.name.rstrip('.') + '.'
308 (tmp_fd, tmpfile) = tempfile.mkstemp()
309 f = os.fdopen(tmp_fd, 'w')
310 if getattr(d, 'nameservers', None):
311 f.write('server %s\n' % d.nameservers[0])
312 if d.type == "A":
313 f.write("update add %s %u A %s\n" % (normalised_name, default_ttl, d.ip))
314 if d.type == "AAAA":
315 f.write("update add %s %u AAAA %s\n" % (normalised_name, default_ttl, d.ip))
316 if d.type == "SRV":
317 if d.existing_port is not None:
318 f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
319 d.existing_port, d.dest))
320 f.write("update add %s %u SRV 0 100 %s %s\n" % (normalised_name, default_ttl, d.port, d.dest))
321 if d.type == "CNAME":
322 f.write("update add %s %u CNAME %s\n" % (normalised_name, default_ttl, d.dest))
323 if d.type == "NS":
324 f.write("update add %s %u NS %s\n" % (normalised_name, default_ttl, d.dest))
325 if opts.verbose:
326 f.write("show\n")
327 f.write("send\n")
328 f.close()
330 global error_count
331 if ccachename:
332 os.environ["KRB5CCNAME"] = ccachename
333 try:
334 cmd = nsupdate_cmd[:]
335 cmd.append(tmpfile)
336 if ccachename:
337 env = {"KRB5CCNAME": ccachename}
338 else:
339 env = {}
340 ret = subprocess.call(cmd, shell=False, env=env)
341 if ret != 0:
342 if opts.fail_immediately:
343 if opts.verbose:
344 print("Failed update with %s" % tmpfile)
345 sys.exit(1)
346 error_count = error_count + 1
347 if opts.verbose:
348 print("Failed nsupdate: %d" % ret)
349 except Exception, estr:
350 if opts.fail_immediately:
351 sys.exit(1)
352 error_count = error_count + 1
353 if opts.verbose:
354 print("Failed nsupdate: %s : %s" % (str(d), estr))
355 os.unlink(tmpfile)
359 def rodc_dns_update(d, t):
360 '''a single DNS update via the RODC netlogon call'''
361 global sub_vars
363 if opts.verbose:
364 print "Calling netlogon RODC update for %s" % d
366 typemap = {
367 netlogon.NlDnsLdapAtSite : netlogon.NlDnsInfoTypeNone,
368 netlogon.NlDnsGcAtSite : netlogon.NlDnsDomainNameAlias,
369 netlogon.NlDnsDsaCname : netlogon.NlDnsDomainNameAlias,
370 netlogon.NlDnsKdcAtSite : netlogon.NlDnsInfoTypeNone,
371 netlogon.NlDnsDcAtSite : netlogon.NlDnsInfoTypeNone,
372 netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
373 netlogon.NlDnsGenericGcAtSite : netlogon.NlDnsDomainNameAlias
376 w = winbind.winbind("irpc:winbind_server", lp)
377 dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
378 dns_names.count = 1
379 name = netlogon.NL_DNS_NAME_INFO()
380 name.type = t
381 name.dns_domain_info_type = typemap[t]
382 name.priority = 0
383 name.weight = 0
384 if d.port is not None:
385 name.port = int(d.port)
386 name.dns_register = True
387 dns_names.names = [ name ]
388 site_name = sub_vars['SITE'].decode('utf-8')
390 global error_count
392 try:
393 ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
394 if ret_names.names[0].status != 0:
395 print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
396 error_count = error_count + 1
397 except RuntimeError, reason:
398 print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
399 error_count = error_count + 1
401 if error_count != 0 and opts.fail_immediately:
402 sys.exit(1)
405 def call_rodc_update(d):
406 '''RODCs need to use the netlogon API for nsupdate'''
407 global lp, sub_vars
409 # we expect failure for 3268 if we aren't a GC
410 if d.port is not None and int(d.port) == 3268:
411 return
413 # map the DNS request to a netlogon update type
414 map = {
415 netlogon.NlDnsLdapAtSite : '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
416 netlogon.NlDnsGcAtSite : '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
417 netlogon.NlDnsDsaCname : '${NTDSGUID}._msdcs.${DNSFOREST}',
418 netlogon.NlDnsKdcAtSite : '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
419 netlogon.NlDnsDcAtSite : '_ldap._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
420 netlogon.NlDnsRfc1510KdcAtSite : '_kerberos._tcp.${SITE}._sites.${DNSDOMAIN}',
421 netlogon.NlDnsGenericGcAtSite : '_gc._tcp.${SITE}._sites.${DNSFOREST}'
424 for t in map:
425 subname = samba.substitute_var(map[t], sub_vars)
426 if subname.lower() == d.name.lower():
427 # found a match - do the update
428 rodc_dns_update(d, t)
429 return
430 if opts.verbose:
431 print("Unable to map to netlogon DNS update: %s" % d)
434 # get the list of DNS entries we should have
435 if opts.update_list:
436 dns_update_list = opts.update_list
437 else:
438 dns_update_list = lp.private_path('dns_update_list')
440 # use our private krb5.conf to avoid problems with the wrong domain
441 # bind9 nsupdate wants the default domain set
442 krb5conf = lp.private_path('krb5.conf')
443 os.environ['KRB5_CONFIG'] = krb5conf
445 file = open(dns_update_list, "r")
447 if opts.nosubs:
448 sub_vars = {}
449 else:
450 samdb = SamDB(url=lp.samdb_url(), session_info=system_session(), lp=lp)
452 # get the substitution dictionary
453 sub_vars = get_subst_vars(samdb)
455 # build up a list of update commands to pass to nsupdate
456 update_list = []
457 dns_list = []
459 dup_set = set()
461 # read each line, and check that the DNS name exists
462 for line in file:
463 line = line.strip()
464 if line == '' or line[0] == "#":
465 continue
466 d = parse_dns_line(line, sub_vars)
467 if d is None:
468 continue
469 if d.type == 'A' and len(IP4s) == 0:
470 continue
471 if d.type == 'AAAA' and len(IP6s) == 0:
472 continue
473 if str(d) not in dup_set:
474 dns_list.append(d)
475 dup_set.add(str(d))
477 # now expand the entries, if any are A record with ip set to $IP
478 # then replace with multiple entries, one for each interface IP
479 for d in dns_list:
480 if d.ip != "$IP":
481 continue
482 if d.type == 'A':
483 d.ip = IP4s[0]
484 for i in range(len(IP4s)-1):
485 d2 = dnsobj(str(d))
486 d2.ip = IP4s[i+1]
487 dns_list.append(d2)
488 if d.type == 'AAAA':
489 d.ip = IP6s[0]
490 for i in range(len(IP6s)-1):
491 d2 = dnsobj(str(d))
492 d2.ip = IP6s[i+1]
493 dns_list.append(d2)
495 # now check if the entries already exist on the DNS server
496 for d in dns_list:
497 if opts.all_names or not check_dns_name(d):
498 update_list.append(d)
500 if len(update_list) == 0:
501 if opts.verbose:
502 print "No DNS updates needed"
503 sys.exit(0)
505 # get our krb5 creds
506 if not opts.nocreds:
507 get_credentials(lp)
509 # ask nsupdate to add entries as needed
510 for d in update_list:
511 if am_rodc:
512 if d.name.lower() == domain.lower():
513 continue
514 if not d.type in [ 'A', 'AAAA' ]:
515 call_rodc_update(d)
516 else:
517 call_nsupdate(d)
518 else:
519 call_nsupdate(d)
521 # delete the ccache if we created it
522 if ccachename is not None:
523 os.unlink(ccachename)
525 if error_count != 0:
526 print("Failed update of %u entries" % error_count)
527 sys.exit(error_count)