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