samba_dnsupdate: Use docstrings, which show up nicely in API docs.
[Samba/vl.git] / source4 / scripting / bin / samba_dnsupdate
blobfee1a08f4fca6850c7fbc6acef652ad56a6b3a89
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 self.dest = None
129 self.port = None
130 self.ip = None
131 self.existing_port = None
132 self.existing_weight = None
133 self.type = list[0]
134 self.name = list[1].lower()
135 if self.type == 'SRV':
136 self.dest = list[2].lower()
137 self.port = list[3]
138 elif self.type in ['A', 'AAAA']:
139 self.ip = list[2] # usually $IP, which gets replaced
140 elif self.type == 'CNAME':
141 self.dest = list[2].lower()
142 elif self.type == 'NS':
143 self.dest = list[2].lower()
144 else:
145 print "Received unexpected DNS reply of type %s" % self.type
146 raise
148 def __str__(self):
149 if d.type == "A": return "%s %s %s" % (self.type, self.name, self.ip)
150 if d.type == "AAAA": return "%s %s %s" % (self.type, self.name, self.ip)
151 if d.type == "SRV": return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
152 if d.type == "CNAME": return "%s %s %s" % (self.type, self.name, self.dest)
153 if d.type == "NS": return "%s %s %s" % (self.type, self.name, self.dest)
156 def parse_dns_line(line, sub_vars):
157 """parse a DNS line from."""
158 if line.startswith("SRV _ldap._tcp.pdc._msdcs.") and not samdb.am_pdc():
159 if opts.verbose:
160 print "Skipping PDC entry (%s) as we are not a PDC" % line
161 return None
162 subline = samba.substitute_var(line, sub_vars)
163 d = dnsobj(subline)
164 return d
167 def hostname_match(h1, h2):
168 """see if two hostnames match."""
169 h1 = str(h1)
170 h2 = str(h2)
171 return h1.lower().rstrip('.') == h2.lower().rstrip('.')
174 def check_dns_name(d):
175 """check that a DNS entry exists."""
176 normalised_name = d.name.rstrip('.') + '.'
177 if opts.verbose:
178 print "Looking for DNS entry %s as %s" % (d, normalised_name)
180 if opts.use_file is not None:
181 try:
182 dns_file = open(opts.use_file, "r")
183 except IOError:
184 return False
186 for line in dns_file:
187 line = line.strip()
188 if line == '' or line[0] == "#":
189 continue
190 if line.lower() == str(d).lower():
191 return True
192 return False
194 resolver = dns.resolver.Resolver()
195 if d.type == "NS":
196 # we need to lookup the nameserver for the parent domain,
197 # and use that to check the NS record
198 parent_domain = '.'.join(normalised_name.split('.')[1:])
199 try:
200 ans = resolver.query(parent_domain, 'NS')
201 except dns.exception.DNSException:
202 if opts.verbose:
203 print "Failed to find parent NS for %s" % d
204 return False
205 nameservers = set()
206 for i in range(len(ans)):
207 try:
208 ns = resolver.query(str(ans[i]), 'A')
209 except dns.exception.DNSException:
210 continue
211 for j in range(len(ns)):
212 nameservers.add(str(ns[j]))
213 d.nameservers = list(nameservers)
215 try:
216 if getattr(d, 'nameservers', None):
217 resolver.nameservers = list(d.nameservers)
218 ans = resolver.query(normalised_name, d.type)
219 except dns.exception.DNSException:
220 if opts.verbose:
221 print "Failed to find DNS entry %s" % d
222 return False
223 if d.type in ['A', 'AAAA']:
224 # we need to be sure that our IP is there
225 for rdata in ans:
226 if str(rdata) == str(d.ip):
227 return True
228 elif d.type == 'CNAME':
229 for i in range(len(ans)):
230 if hostname_match(ans[i].target, d.dest):
231 return True
232 elif d.type == 'NS':
233 for i in range(len(ans)):
234 if hostname_match(ans[i].target, d.dest):
235 return True
236 elif d.type == 'SRV':
237 for rdata in ans:
238 if opts.verbose:
239 print "Checking %s against %s" % (rdata, d)
240 if hostname_match(rdata.target, d.dest):
241 if str(rdata.port) == str(d.port):
242 return True
243 else:
244 d.existing_port = str(rdata.port)
245 d.existing_weight = str(rdata.weight)
247 if opts.verbose:
248 print "Failed to find matching DNS entry %s" % d
250 return False
253 def get_subst_vars(samdb):
254 """get the list of substitution vars."""
255 global lp, am_rodc
256 vars = {}
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 def call_nsupdate(d):
272 """call nsupdate for an entry."""
273 global ccachename, nsupdate_cmd
275 if opts.verbose:
276 print "Calling nsupdate for %s" % d
278 if opts.use_file is not None:
279 wfile = open(opts.use_file, 'a')
280 fcntl.lockf(wfile, fcntl.LOCK_EX)
281 wfile.write(str(d)+"\n")
282 fcntl.lockf(wfile, fcntl.LOCK_UN)
283 return
285 normalised_name = d.name.rstrip('.') + '.'
287 (tmp_fd, tmpfile) = tempfile.mkstemp()
288 f = os.fdopen(tmp_fd, 'w')
289 if getattr(d, 'nameservers', None):
290 f.write('server %s\n' % d.nameservers[0])
291 if d.type == "A":
292 f.write("update add %s %u A %s\n" % (normalised_name, default_ttl, d.ip))
293 if d.type == "AAAA":
294 f.write("update add %s %u AAAA %s\n" % (normalised_name, default_ttl, d.ip))
295 if d.type == "SRV":
296 if d.existing_port is not None:
297 f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
298 d.existing_port, d.dest))
299 f.write("update add %s %u SRV 0 100 %s %s\n" % (normalised_name, default_ttl, d.port, d.dest))
300 if d.type == "CNAME":
301 f.write("update add %s %u CNAME %s\n" % (normalised_name, default_ttl, d.dest))
302 if d.type == "NS":
303 f.write("update add %s %u NS %s\n" % (normalised_name, default_ttl, d.dest))
304 if opts.verbose:
305 f.write("show\n")
306 f.write("send\n")
307 f.close()
309 global error_count
310 if ccachename:
311 os.environ["KRB5CCNAME"] = ccachename
312 try:
313 cmd = nsupdate_cmd[:]
314 cmd.append(tmpfile)
315 if ccachename:
316 env = {"KRB5CCNAME": ccachename}
317 else:
318 env = {}
319 ret = subprocess.call(cmd, shell=False, env=env)
320 if ret != 0:
321 if opts.fail_immediately:
322 if opts.verbose:
323 print("Failed update with %s" % tmpfile)
324 sys.exit(1)
325 error_count = error_count + 1
326 if opts.verbose:
327 print("Failed nsupdate: %d" % ret)
328 except Exception, estr:
329 if opts.fail_immediately:
330 sys.exit(1)
331 error_count = error_count + 1
332 if opts.verbose:
333 print("Failed nsupdate: %s : %s" % (str(d), estr))
334 os.unlink(tmpfile)
338 def rodc_dns_update(d, t):
339 '''a single DNS update via the RODC netlogon call'''
340 global sub_vars
342 if opts.verbose:
343 print "Calling netlogon RODC update for %s" % d
345 typemap = {
346 netlogon.NlDnsLdapAtSite : netlogon.NlDnsInfoTypeNone,
347 netlogon.NlDnsGcAtSite : netlogon.NlDnsDomainNameAlias,
348 netlogon.NlDnsDsaCname : netlogon.NlDnsDomainNameAlias,
349 netlogon.NlDnsKdcAtSite : netlogon.NlDnsInfoTypeNone,
350 netlogon.NlDnsDcAtSite : netlogon.NlDnsInfoTypeNone,
351 netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
352 netlogon.NlDnsGenericGcAtSite : netlogon.NlDnsDomainNameAlias
355 w = winbind.winbind("irpc:winbind_server", lp)
356 dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
357 dns_names.count = 1
358 name = netlogon.NL_DNS_NAME_INFO()
359 name.type = t
360 name.dns_domain_info_type = typemap[t]
361 name.priority = 0
362 name.weight = 0
363 if d.port is not None:
364 name.port = int(d.port)
365 name.dns_register = True
366 dns_names.names = [ name ]
367 site_name = sub_vars['SITE'].decode('utf-8')
369 global error_count
371 try:
372 ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
373 if ret_names.names[0].status != 0:
374 print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
375 error_count = error_count + 1
376 except RuntimeError, reason:
377 print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
378 error_count = error_count + 1
380 if error_count != 0 and opts.fail_immediately:
381 sys.exit(1)
384 def call_rodc_update(d):
385 '''RODCs need to use the netlogon API for nsupdate'''
386 global lp, sub_vars
388 # we expect failure for 3268 if we aren't a GC
389 if d.port is not None and int(d.port) == 3268:
390 return
392 # map the DNS request to a netlogon update type
393 map = {
394 netlogon.NlDnsLdapAtSite : '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
395 netlogon.NlDnsGcAtSite : '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
396 netlogon.NlDnsDsaCname : '${NTDSGUID}._msdcs.${DNSFOREST}',
397 netlogon.NlDnsKdcAtSite : '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
398 netlogon.NlDnsDcAtSite : '_ldap._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
399 netlogon.NlDnsRfc1510KdcAtSite : '_kerberos._tcp.${SITE}._sites.${DNSDOMAIN}',
400 netlogon.NlDnsGenericGcAtSite : '_gc._tcp.${SITE}._sites.${DNSFOREST}'
403 for t in map:
404 subname = samba.substitute_var(map[t], sub_vars)
405 if subname.lower() == d.name.lower():
406 # found a match - do the update
407 rodc_dns_update(d, t)
408 return
409 if opts.verbose:
410 print("Unable to map to netlogon DNS update: %s" % d)
413 # get the list of DNS entries we should have
414 if opts.update_list:
415 dns_update_list = opts.update_list
416 else:
417 dns_update_list = lp.private_path('dns_update_list')
419 # use our private krb5.conf to avoid problems with the wrong domain
420 # bind9 nsupdate wants the default domain set
421 krb5conf = lp.private_path('krb5.conf')
422 os.environ['KRB5_CONFIG'] = krb5conf
424 file = open(dns_update_list, "r")
426 samdb = SamDB(url=lp.samdb_url(), session_info=system_session(), lp=lp)
428 # get the substitution dictionary
429 sub_vars = get_subst_vars(samdb)
431 # build up a list of update commands to pass to nsupdate
432 update_list = []
433 dns_list = []
435 dup_set = set()
437 # read each line, and check that the DNS name exists
438 for line in file:
439 line = line.strip()
440 if line == '' or line[0] == "#":
441 continue
442 d = parse_dns_line(line, sub_vars)
443 if d is None:
444 continue
445 if d.type == 'A' and len(IP4s) == 0:
446 continue
447 if d.type == 'AAAA' and len(IP6s) == 0:
448 continue
449 if str(d) not in dup_set:
450 dns_list.append(d)
451 dup_set.add(str(d))
453 # now expand the entries, if any are A record with ip set to $IP
454 # then replace with multiple entries, one for each interface IP
455 for d in dns_list:
456 if d.ip != "$IP":
457 continue
458 if d.type == 'A':
459 d.ip = IP4s[0]
460 for i in range(len(IP4s)-1):
461 d2 = dnsobj(str(d))
462 d2.ip = IP4s[i+1]
463 dns_list.append(d2)
464 if d.type == 'AAAA':
465 d.ip = IP6s[0]
466 for i in range(len(IP6s)-1):
467 d2 = dnsobj(str(d))
468 d2.ip = IP6s[i+1]
469 dns_list.append(d2)
471 # now check if the entries already exist on the DNS server
472 for d in dns_list:
473 if opts.all_names or not check_dns_name(d):
474 update_list.append(d)
476 if len(update_list) == 0:
477 if opts.verbose:
478 print "No DNS updates needed"
479 sys.exit(0)
481 # get our krb5 creds
482 if not opts.nocreds:
483 get_credentials(lp)
485 # ask nsupdate to add entries as needed
486 for d in update_list:
487 if am_rodc:
488 if d.name.lower() == domain.lower():
489 continue
490 if not d.type in [ 'A', 'AAAA' ]:
491 call_rodc_update(d)
492 else:
493 call_nsupdate(d)
494 else:
495 call_nsupdate(d)
497 # delete the ccache if we created it
498 if ccachename is not None:
499 os.unlink(ccachename)
501 if error_count != 0:
502 print("Failed update of %u entries" % error_count)
503 sys.exit(error_count)