Merge branch 'master' of ctdb into 'master' of samba
[kai/samba-autobuild/.git] / source4 / scripting / bin / samba_dnsupdate
1 #!/usr/bin/env python
2 # vim: expandtab
3 #
4 # update our DNS names using TSIG-GSS
5 #
6 # Copyright (C) Andrew Tridgell 2010
7 #
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.
12 #
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.
17 #
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/>.
20
21
22 import os
23 import fcntl
24 import sys
25 import tempfile
26 import subprocess
27
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'
31
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"
37
38 # Find right directory when running from source tree
39 sys.path.insert(0, "bin/python")
40
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
48
49 samba.ensure_external_module("dns", "dnspython")
50 import dns.resolver
51 import dns.exception
52
53 default_ttl = 900
54 am_rodc = False
55 error_count = 0
56
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")
69
70 creds = None
71 ccachename = None
72
73 opts, args = parser.parse_args()
74
75 if len(args) != 0:
76     parser.print_usage()
77     sys.exit(1)
78
79 lp = sambaopts.get_loadparm()
80
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
87
88 IPs = samba.interface_ips(lp, all_interfaces)
89 nsupdate_cmd = lp.get('nsupdate command')
90
91 if len(IPs) == 0:
92     print "No IP interfaces - skipping DNS updates"
93     sys.exit(0)
94
95 IP6s = []
96 IP4s = []
97 for i in IPs:
98     if i.find(':') != -1:
99         IP6s.append(i)
100     else:
101         IP4s.append(i)
102
103
104 if opts.verbose:
105     print "IPs: %s" % IPs
106
107
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     try:
120         creds.get_named_ccache(lp, ccachename)
121     except RuntimeError as e:
122         os.unlink(ccachename)
123         raise e
124
125
126 class dnsobj(object):
127     """an object to hold a parsed DNS line"""
128
129     def __init__(self, string_form):
130         list = string_form.split()
131         if len(list) < 3:
132             raise Exception("Invalid DNS entry %r" % string_form)
133         self.dest = None
134         self.port = None
135         self.ip = None
136         self.existing_port = None
137         self.existing_weight = None
138         self.type = list[0]
139         self.name = list[1].lower()
140         if self.type == 'SRV':
141             if len(list) < 4:
142                 raise Exception("Invalid DNS entry %r" % string_form)
143             self.dest = list[2].lower()
144             self.port = list[3]
145         elif self.type in ['A', 'AAAA']:
146             self.ip   = list[2] # usually $IP, which gets replaced
147         elif self.type == 'CNAME':
148             self.dest = list[2].lower()
149         elif self.type == 'NS':
150             self.dest = list[2].lower()
151         else:
152             raise Exception("Received unexpected DNS reply of type %s" % self.type)
153
154     def __str__(self):
155         if d.type == "A":
156             return "%s %s %s" % (self.type, self.name, self.ip)
157         if d.type == "AAAA":
158             return "%s %s %s" % (self.type, self.name, self.ip)
159         if d.type == "SRV":
160             return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
161         if d.type == "CNAME":
162             return "%s %s %s" % (self.type, self.name, self.dest)
163         if d.type == "NS":
164             return "%s %s %s" % (self.type, self.name, self.dest)
165
166
167 def parse_dns_line(line, sub_vars):
168     """parse a DNS line from."""
169     if line.startswith("SRV _ldap._tcp.pdc._msdcs.") and not samdb.am_pdc():
170         if opts.verbose:
171             print "Skipping PDC entry (%s) as we are not a PDC" % line
172         return None
173     subline = samba.substitute_var(line, sub_vars)
174     return dnsobj(subline)
175
176
177 def hostname_match(h1, h2):
178     """see if two hostnames match."""
179     h1 = str(h1)
180     h2 = str(h2)
181     return h1.lower().rstrip('.') == h2.lower().rstrip('.')
182
183
184 def check_dns_name(d):
185     """check that a DNS entry exists."""
186     normalised_name = d.name.rstrip('.') + '.'
187     if opts.verbose:
188         print "Looking for DNS entry %s as %s" % (d, normalised_name)
189
190     if opts.use_file is not None:
191         try:
192             dns_file = open(opts.use_file, "r")
193         except IOError:
194             return False
195
196         for line in dns_file:
197             line = line.strip()
198             if line == '' or line[0] == "#":
199                 continue
200             if line.lower() == str(d).lower():
201                 return True
202         return False
203
204     resolver = dns.resolver.Resolver()
205     if d.type == "NS":
206         # we need to lookup the nameserver for the parent domain,
207         # and use that to check the NS record
208         parent_domain = '.'.join(normalised_name.split('.')[1:])
209         try:
210             ans = resolver.query(parent_domain, 'NS')
211         except dns.exception.DNSException:
212             if opts.verbose:
213                 print "Failed to find parent NS for %s" % d
214             return False
215         nameservers = set()
216         for i in range(len(ans)):
217             try:
218                 ns = resolver.query(str(ans[i]), 'A')
219             except dns.exception.DNSException:
220                 continue
221             for j in range(len(ns)):
222                 nameservers.add(str(ns[j]))
223         d.nameservers = list(nameservers)
224
225     try:
226         if getattr(d, 'nameservers', None):
227             resolver.nameservers = list(d.nameservers)
228         ans = resolver.query(normalised_name, d.type)
229     except dns.exception.DNSException:
230         if opts.verbose:
231             print "Failed to find DNS entry %s" % d
232         return False
233     if d.type in ['A', 'AAAA']:
234         # we need to be sure that our IP is there
235         for rdata in ans:
236             if str(rdata) == str(d.ip):
237                 return True
238     elif d.type == 'CNAME':
239         for i in range(len(ans)):
240             if hostname_match(ans[i].target, d.dest):
241                 return True
242     elif d.type == 'NS':
243         for i in range(len(ans)):
244             if hostname_match(ans[i].target, d.dest):
245                 return True
246     elif d.type == 'SRV':
247         for rdata in ans:
248             if opts.verbose:
249                 print "Checking %s against %s" % (rdata, d)
250             if hostname_match(rdata.target, d.dest):
251                 if str(rdata.port) == str(d.port):
252                     return True
253                 else:
254                     d.existing_port     = str(rdata.port)
255                     d.existing_weight = str(rdata.weight)
256
257     if opts.verbose:
258         print "Failed to find matching DNS entry %s" % d
259
260     return False
261
262
263 def get_subst_vars(samdb):
264     """get the list of substitution vars."""
265     global lp, am_rodc
266     vars = {}
267
268     vars['DNSDOMAIN'] = samdb.domain_dns_name()
269     vars['DNSFOREST'] = samdb.forest_dns_name()
270     vars['HOSTNAME']  = samdb.host_dns_name()
271     vars['NTDSGUID']  = samdb.get_ntds_GUID()
272     vars['SITE']      = samdb.server_site_name()
273     res = samdb.search(base=samdb.get_default_basedn(), scope=SCOPE_BASE, attrs=["objectGUID"])
274     guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
275     vars['DOMAINGUID'] = guid
276     am_rodc = samdb.am_rodc()
277
278     return vars
279
280
281 def call_nsupdate(d):
282     """call nsupdate for an entry."""
283     global ccachename, nsupdate_cmd, krb5conf
284
285     if opts.verbose:
286         print "Calling nsupdate for %s" % d
287
288     if opts.use_file is not None:
289         try:
290             rfile = open(opts.use_file, 'r+')
291         except IOError:
292             # Perhaps create it
293             rfile = open(opts.use_file, 'w+')
294             # Open it for reading again, in case someone else got to it first
295             rfile = open(opts.use_file, 'r+')
296         fcntl.lockf(rfile, fcntl.LOCK_EX)
297         (file_dir, file_name) = os.path.split(opts.use_file)
298         (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
299         wfile = os.fdopen(tmp_fd, 'a')
300         rfile.seek(0)
301         for line in rfile:
302             wfile.write(line)
303         wfile.write(str(d)+"\n")
304         os.rename(tmpfile, opts.use_file)
305         fcntl.lockf(rfile, fcntl.LOCK_UN)
306         return
307
308     normalised_name = d.name.rstrip('.') + '.'
309
310     (tmp_fd, tmpfile) = tempfile.mkstemp()
311     f = os.fdopen(tmp_fd, 'w')
312     if getattr(d, 'nameservers', None):
313         f.write('server %s\n' % d.nameservers[0])
314     if d.type == "A":
315         f.write("update add %s %u A %s\n" % (normalised_name, default_ttl, d.ip))
316     if d.type == "AAAA":
317         f.write("update add %s %u AAAA %s\n" % (normalised_name, default_ttl, d.ip))
318     if d.type == "SRV":
319         if d.existing_port is not None:
320             f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
321                                                            d.existing_port, d.dest))
322         f.write("update add %s %u SRV 0 100 %s %s\n" % (normalised_name, default_ttl, d.port, d.dest))
323     if d.type == "CNAME":
324         f.write("update add %s %u CNAME %s\n" % (normalised_name, default_ttl, d.dest))
325     if d.type == "NS":
326         f.write("update add %s %u NS %s\n" % (normalised_name, default_ttl, d.dest))
327     if opts.verbose:
328         f.write("show\n")
329     f.write("send\n")
330     f.close()
331
332     global error_count
333     if ccachename:
334         os.environ["KRB5CCNAME"] = ccachename
335     try:
336         cmd = nsupdate_cmd[:]
337         cmd.append(tmpfile)
338         env = {}
339         if krb5conf:
340             env["KRB5_CONFIG"] = krb5conf
341         if ccachename:
342             env["KRB5CCNAME"] = ccachename
343         ret = subprocess.call(cmd, shell=False, env=env)
344         if ret != 0:
345             if opts.fail_immediately:
346                 if opts.verbose:
347                     print("Failed update with %s" % tmpfile)
348                 sys.exit(1)
349             error_count = error_count + 1
350             if opts.verbose:
351                 print("Failed nsupdate: %d" % ret)
352     except Exception, estr:
353         if opts.fail_immediately:
354             sys.exit(1)
355         error_count = error_count + 1
356         if opts.verbose:
357             print("Failed nsupdate: %s : %s" % (str(d), estr))
358     os.unlink(tmpfile)
359
360
361
362 def rodc_dns_update(d, t):
363     '''a single DNS update via the RODC netlogon call'''
364     global sub_vars
365
366     if opts.verbose:
367         print "Calling netlogon RODC update for %s" % d
368
369     typemap = {
370         netlogon.NlDnsLdapAtSite       : netlogon.NlDnsInfoTypeNone,
371         netlogon.NlDnsGcAtSite         : netlogon.NlDnsDomainNameAlias,
372         netlogon.NlDnsDsaCname         : netlogon.NlDnsDomainNameAlias,
373         netlogon.NlDnsKdcAtSite        : netlogon.NlDnsInfoTypeNone,
374         netlogon.NlDnsDcAtSite         : netlogon.NlDnsInfoTypeNone,
375         netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
376         netlogon.NlDnsGenericGcAtSite  : netlogon.NlDnsDomainNameAlias
377         }
378
379     w = winbind.winbind("irpc:winbind_server", lp)
380     dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
381     dns_names.count = 1
382     name = netlogon.NL_DNS_NAME_INFO()
383     name.type = t
384     name.dns_domain_info_type = typemap[t]
385     name.priority = 0
386     name.weight   = 0
387     if d.port is not None:
388         name.port = int(d.port)
389     name.dns_register = True
390     dns_names.names = [ name ]
391     site_name = sub_vars['SITE'].decode('utf-8')
392
393     global error_count
394
395     try:
396         ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
397         if ret_names.names[0].status != 0:
398             print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
399             error_count = error_count + 1
400     except RuntimeError, reason:
401         print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
402         error_count = error_count + 1
403
404     if error_count != 0 and opts.fail_immediately:
405         sys.exit(1)
406
407
408 def call_rodc_update(d):
409     '''RODCs need to use the netlogon API for nsupdate'''
410     global lp, sub_vars
411
412     # we expect failure for 3268 if we aren't a GC
413     if d.port is not None and int(d.port) == 3268:
414         return
415
416     # map the DNS request to a netlogon update type
417     map = {
418         netlogon.NlDnsLdapAtSite       : '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
419         netlogon.NlDnsGcAtSite         : '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
420         netlogon.NlDnsDsaCname         : '${NTDSGUID}._msdcs.${DNSFOREST}',
421         netlogon.NlDnsKdcAtSite        : '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
422         netlogon.NlDnsDcAtSite         : '_ldap._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
423         netlogon.NlDnsRfc1510KdcAtSite : '_kerberos._tcp.${SITE}._sites.${DNSDOMAIN}',
424         netlogon.NlDnsGenericGcAtSite  : '_gc._tcp.${SITE}._sites.${DNSFOREST}'
425         }
426
427     for t in map:
428         subname = samba.substitute_var(map[t], sub_vars)
429         if subname.lower() == d.name.lower():
430             # found a match - do the update
431             rodc_dns_update(d, t)
432             return
433     if opts.verbose:
434         print("Unable to map to netlogon DNS update: %s" % d)
435
436
437 # get the list of DNS entries we should have
438 if opts.update_list:
439     dns_update_list = opts.update_list
440 else:
441     dns_update_list = lp.private_path('dns_update_list')
442
443 # use our private krb5.conf to avoid problems with the wrong domain
444 # bind9 nsupdate wants the default domain set
445 krb5conf = lp.private_path('krb5.conf')
446 os.environ['KRB5_CONFIG'] = krb5conf
447
448 file = open(dns_update_list, "r")
449
450 if opts.nosubs:
451     sub_vars = {}
452 else:
453     samdb = SamDB(url=lp.samdb_url(), session_info=system_session(), lp=lp)
454
455     # get the substitution dictionary
456     sub_vars = get_subst_vars(samdb)
457
458 # build up a list of update commands to pass to nsupdate
459 update_list = []
460 dns_list = []
461
462 dup_set = set()
463
464 # read each line, and check that the DNS name exists
465 for line in file:
466     line = line.strip()
467     if line == '' or line[0] == "#":
468         continue
469     d = parse_dns_line(line, sub_vars)
470     if d is None:
471         continue
472     if d.type == 'A' and len(IP4s) == 0:
473         continue
474     if d.type == 'AAAA' and len(IP6s) == 0:
475         continue
476     if str(d) not in dup_set:
477         dns_list.append(d)
478         dup_set.add(str(d))
479
480 # now expand the entries, if any are A record with ip set to $IP
481 # then replace with multiple entries, one for each interface IP
482 for d in dns_list:
483     if d.ip != "$IP":
484         continue
485     if d.type == 'A':
486         d.ip = IP4s[0]
487         for i in range(len(IP4s)-1):
488             d2 = dnsobj(str(d))
489             d2.ip = IP4s[i+1]
490             dns_list.append(d2)
491     if d.type == 'AAAA':
492         d.ip = IP6s[0]
493         for i in range(len(IP6s)-1):
494             d2 = dnsobj(str(d))
495             d2.ip = IP6s[i+1]
496             dns_list.append(d2)
497
498 # now check if the entries already exist on the DNS server
499 for d in dns_list:
500     if opts.all_names or not check_dns_name(d):
501         update_list.append(d)
502
503 if len(update_list) == 0:
504     if opts.verbose:
505         print "No DNS updates needed"
506     sys.exit(0)
507
508 # get our krb5 creds
509 if not opts.nocreds:
510     get_credentials(lp)
511
512 # ask nsupdate to add entries as needed
513 for d in update_list:
514     if am_rodc:
515         if d.name.lower() == domain.lower():
516             continue
517         if not d.type in [ 'A', 'AAAA' ]:
518             call_rodc_update(d)
519         else:
520             call_nsupdate(d)
521     else:
522         call_nsupdate(d)
523
524 # delete the ccache if we created it
525 if ccachename is not None:
526     os.unlink(ccachename)
527
528 if error_count != 0:
529     print("Failed update of %u entries" % error_count)
530 sys.exit(error_count)