s4-dns: catch more expections in samba_dnsupdate
[samba.git] / source4 / scripting / bin / samba_dnsupdate
1 #!/usr/bin/env python
2 #
3 # update our DNS names using TSIG-GSS
4 #
5 # Copyright (C) Andrew Tridgell 2010
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20
21 import os
22 import fcntl
23 import sys
24 import tempfile
25 import subprocess
26
27 # ensure we get messages out immediately, so they get in the samba logs,
28 # and don't get swallowed by a timeout
29 os.putenv('PYTHONUNBUFFERED', '1')
30
31 # forcing GMT avoids a problem in some timezones with kerberos. Both MIT
32 # heimdal can get mutual authentication errors due to the 24 second difference
33 # between UTC and GMT when using some zone files (eg. the PDT zone from
34 # the US)
35 os.putenv("TZ", "GMT")
36
37 # Find right directory when running from source tree
38 sys.path.insert(0, "bin/python")
39
40 import samba
41 import optparse
42 from samba import getopt as options
43 from ldb import SCOPE_BASE
44 from samba.auth import system_session
45 from samba.samdb import SamDB
46 from samba.dcerpc import netlogon, winbind
47
48 samba.ensure_external_module("dns", "dnspython")
49 import dns.resolver as resolver
50
51 default_ttl = 900
52 am_rodc = False
53 error_count = 0
54
55 parser = optparse.OptionParser("samba_dnsupdate")
56 sambaopts = options.SambaOptions(parser)
57 parser.add_option_group(sambaopts)
58 parser.add_option_group(options.VersionOptions(parser))
59 parser.add_option("--verbose", action="store_true")
60 parser.add_option("--all-names", action="store_true")
61 parser.add_option("--all-interfaces", action="store_true")
62 parser.add_option("--use-file", type="string", help="Use a file, rather than real DNS calls")
63 parser.add_option("--update-list", type="string", help="Add DNS names from the given file")
64 parser.add_option("--fail-immediately", action='store_true', help="Exit on first failure")
65
66 creds = None
67 ccachename = None
68
69 opts, args = parser.parse_args()
70
71 if len(args) != 0:
72     parser.print_usage()
73     sys.exit(1)
74
75 lp = sambaopts.get_loadparm()
76
77 domain = lp.get("realm")
78 host = lp.get("netbios name")
79 if opts.all_interfaces:
80     all_interfaces = True
81 else:
82     all_interfaces = False
83
84 IPs = samba.interface_ips(lp, all_interfaces)
85 nsupdate_cmd = lp.get('nsupdate command')
86
87 if len(IPs) == 0:
88     print "No IP interfaces - skipping DNS updates"
89     sys.exit(0)
90
91 if opts.verbose:
92     print "IPs: %s" % IPs
93
94 ########################################################
95 # get credentials if we haven't got them already
96 def get_credentials(lp):
97     from samba import credentials
98     global ccachename, creds
99     if creds is not None:
100         return
101     creds = credentials.Credentials()
102     creds.guess(lp)
103     creds.set_machine_account(lp)
104     creds.set_krb_forwardable(credentials.NO_KRB_FORWARDABLE)
105     (tmp_fd, ccachename) = tempfile.mkstemp()
106     creds.get_named_ccache(lp, ccachename)
107
108
109 #############################################
110 # an object to hold a parsed DNS line
111 class dnsobj(object):
112     def __init__(self, string_form):
113         list = string_form.split()
114         self.dest = None
115         self.port = None
116         self.ip = None
117         self.existing_port = None
118         self.existing_weight = None
119         self.type = list[0]
120         self.name = list[1].lower()
121         if self.type == 'SRV':
122             self.dest = list[2].lower()
123             self.port = list[3]
124         elif self.type == 'A':
125             self.ip   = list[2] # usually $IP, which gets replaced
126         elif self.type == 'CNAME':
127             self.dest = list[2].lower()
128         else:
129             print "Received unexpected DNS reply of type %s" % self.type
130             raise
131
132     def __str__(self):
133         if d.type == "A":     return "%s %s %s" % (self.type, self.name, self.ip)
134         if d.type == "SRV":   return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
135         if d.type == "CNAME": return "%s %s %s" % (self.type, self.name, self.dest)
136
137
138 ################################################
139 # parse a DNS line from
140 def parse_dns_line(line, sub_vars):
141     subline = samba.substitute_var(line, sub_vars)
142     d = dnsobj(subline)
143     return d
144
145 ############################################
146 # see if two hostnames match
147 def hostname_match(h1, h2):
148     h1 = str(h1)
149     h2 = str(h2)
150     return h1.lower().rstrip('.') == h2.lower().rstrip('.')
151
152
153 ############################################
154 # check that a DNS entry exists
155 def check_dns_name(d):
156     normalised_name = d.name.rstrip('.') + '.'
157     if opts.verbose:
158         print "Looking for DNS entry %s as %s" % (d, normalised_name)
159  
160     if opts.use_file is not None:
161         try:
162             dns_file = open(opts.use_file, "r")
163         except IOError:
164             return False
165         
166         for line in dns_file:
167             line = line.strip()
168             if line == '' or line[0] == "#":
169                 continue
170             if line.lower() == str(d).lower():
171                 return True
172         return False
173
174     try:
175         ans = resolver.query(normalised_name, d.type)
176     except resolver.NXDOMAIN:
177         return False
178     if d.type == 'A':
179         # we need to be sure that our IP is there
180         for rdata in ans:
181             if str(rdata) == str(d.ip):
182                 return True
183     if d.type == 'CNAME':
184         for i in range(len(ans)):
185             if hostname_match(ans[i].target, d.dest):
186                 return True
187     if d.type == 'SRV':
188         for rdata in ans:
189             if opts.verbose:
190                 print "Checking %s against %s" % (rdata, d)
191             if hostname_match(rdata.target, d.dest):
192                 if str(rdata.port) == str(d.port):
193                     return True
194                 else:
195                     d.existing_port     = str(rdata.port)
196                     d.existing_weight = str(rdata.weight)
197     if opts.verbose:
198         print "Failed to find DNS entry %s" % d
199
200     return False
201
202
203 ###########################################
204 # get the list of substitution vars
205 def get_subst_vars():
206     global lp, am_rodc
207     vars = {}
208
209     samdb = SamDB(url=lp.get("sam database"), session_info=system_session(),
210                   lp=lp)
211
212     vars['DNSDOMAIN'] = lp.get('realm').lower()
213     vars['DNSFOREST'] = lp.get('realm').lower()
214     vars['HOSTNAME']  = lp.get('netbios name').lower() + "." + vars['DNSDOMAIN']
215     vars['NTDSGUID']  = samdb.get_ntds_GUID()
216     vars['SITE']      = samdb.server_site_name()
217     res = samdb.search(base=None, scope=SCOPE_BASE, attrs=["objectGUID"])
218     guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
219     vars['DOMAINGUID'] = guid
220     am_rodc = samdb.am_rodc()
221
222     return vars
223
224
225 ############################################
226 # call nsupdate for an entry
227 def call_nsupdate(d):
228     global ccachename, nsupdate_cmd
229
230     if opts.verbose:
231         print "Calling nsupdate for %s" % d
232
233     if opts.use_file is not None:
234         wfile = open(opts.use_file, 'a')
235         fcntl.lockf(wfile, fcntl.LOCK_EX)
236         wfile.write(str(d)+"\n")
237         fcntl.lockf(wfile, fcntl.LOCK_UN)
238         return
239
240     normalised_name = d.name.rstrip('.') + '.'
241
242     (tmp_fd, tmpfile) = tempfile.mkstemp()
243     f = os.fdopen(tmp_fd, 'w')
244     if d.type == "A":
245         f.write("update add %s %u A %s\n" % (normalised_name, default_ttl, d.ip))
246     if d.type == "SRV":
247         if d.existing_port is not None:
248             f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
249                                                            d.existing_port, d.dest))
250         f.write("update add %s %u SRV 0 100 %s %s\n" % (normalised_name, default_ttl, d.port, d.dest))
251     if d.type == "CNAME":
252         f.write("update add %s %u CNAME %s\n" % (normalised_name, default_ttl, d.dest))
253     if opts.verbose:
254         f.write("show\n")
255     f.write("send\n")
256     f.close()
257
258     os.putenv("KRB5CCNAME", ccachename)
259     try:
260         cmd = "%s %s" % (nsupdate_cmd, tmpfile)
261         subprocess.check_call(cmd, shell=True)
262     except Exception, estr:
263         global error_count
264         if opts.fail_immediately:
265             sys.exit(1)
266         error_count = error_count + 1
267         if opts.verbose:
268             print("Failed nsupdate: %s : %s" % (str(d), estr))
269     os.unlink(tmpfile)
270
271
272
273 def rodc_dns_update(d, t):
274     '''a single DNS update via the RODC netlogon call'''
275     global sub_vars
276
277     if opts.verbose:
278         print "Calling netlogon RODC update for %s" % d
279
280     typemap = {
281         netlogon.NlDnsLdapAtSite       : netlogon.NlDnsInfoTypeNone,
282         netlogon.NlDnsGcAtSite         : netlogon.NlDnsDomainNameAlias,
283         netlogon.NlDnsDsaCname         : netlogon.NlDnsDomainNameAlias,
284         netlogon.NlDnsKdcAtSite        : netlogon.NlDnsInfoTypeNone,
285         netlogon.NlDnsDcAtSite         : netlogon.NlDnsInfoTypeNone,
286         netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
287         netlogon.NlDnsGenericGcAtSite  : netlogon.NlDnsDomainNameAlias
288         }
289
290     w = winbind.winbind("irpc:winbind_server", lp)
291     dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
292     dns_names.count = 1
293     name = netlogon.NL_DNS_NAME_INFO()
294     name.type = t
295     name.dns_domain_info_type = typemap[t]
296     name.priority = 0
297     name.weight   = 0
298     if d.port is not None:
299         name.port = int(d.port)
300     name.dns_register = True
301     dns_names.names = [ name ]
302     site_name = sub_vars['SITE'].decode('utf-8')
303
304     try:
305         ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
306         if ret_names.names[0].status != 0:
307             print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
308     except RuntimeError, reason:
309         print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
310
311
312 def call_rodc_update(d):
313     '''RODCs need to use the netlogon API for nsupdate'''
314     global lp, sub_vars
315
316     # we expect failure for 3268 if we aren't a GC
317     if d.port is not None and int(d.port) == 3268:
318         return
319
320     # map the DNS request to a netlogon update type
321     map = {
322         netlogon.NlDnsLdapAtSite       : '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
323         netlogon.NlDnsGcAtSite         : '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
324         netlogon.NlDnsDsaCname         : '${NTDSGUID}._msdcs.${DNSFOREST}',
325         netlogon.NlDnsKdcAtSite        : '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
326         netlogon.NlDnsDcAtSite         : '_ldap._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
327         netlogon.NlDnsRfc1510KdcAtSite : '_kerberos._tcp.${SITE}._sites.${DNSDOMAIN}',
328         netlogon.NlDnsGenericGcAtSite  : '_gc._tcp.${SITE}._sites.${DNSFOREST}'
329         }
330
331     for t in map:
332         subname = samba.substitute_var(map[t], sub_vars)
333         if subname.lower() == d.name.lower():
334             # found a match - do the update
335             rodc_dns_update(d, t)
336             return
337     if opts.verbose:
338         print("Unable to map to netlogon DNS update: %s" % d)
339
340
341 # get the list of DNS entries we should have
342 if opts.update_list:
343     dns_update_list = opts.update_list
344 else:
345     dns_update_list = lp.private_path('dns_update_list')
346
347 # use our private krb5.conf to avoid problems with the wrong domain
348 # bind9 nsupdate wants the default domain set
349 krb5conf = lp.private_path('krb5.conf')
350 os.putenv('KRB5_CONFIG', krb5conf)
351
352 file = open(dns_update_list, "r")
353
354 # get the substitution dictionary
355 sub_vars = get_subst_vars()
356
357 # build up a list of update commands to pass to nsupdate
358 update_list = []
359 dns_list = []
360
361 # read each line, and check that the DNS name exists
362 for line in file:
363     line = line.strip()
364     if line == '' or line[0] == "#":
365         continue
366     d = parse_dns_line(line, sub_vars)
367     dns_list.append(d)
368
369 # now expand the entries, if any are A record with ip set to $IP
370 # then replace with multiple entries, one for each interface IP
371 for d in dns_list:
372     if d.type == 'A' and d.ip == "$IP":
373         d.ip = IPs[0]
374         for i in range(len(IPs)-1):
375             d2 = dnsobj(str(d))
376             d2.ip = IPs[i+1]
377             dns_list.append(d2)
378
379 # now check if the entries already exist on the DNS server
380 for d in dns_list:
381     if opts.all_names or not check_dns_name(d):
382         update_list.append(d)
383
384 if len(update_list) == 0:
385     if opts.verbose:
386         print "No DNS updates needed"
387     sys.exit(0)
388
389 # get our krb5 creds
390 get_credentials(lp)
391
392 # ask nsupdate to add entries as needed
393 for d in update_list:
394     if am_rodc:
395         if d.name.lower() == domain.lower():
396             continue
397         if d.type != 'A':
398             call_rodc_update(d)
399         else:
400             call_nsupdate(d)
401     else:
402         call_nsupdate(d)
403
404 # delete the ccache if we created it
405 if ccachename is not None:
406     os.unlink(ccachename)
407
408 if error_count != 0:
409     print("Failed update of %u entries" % error_count)
410 sys.exit(error_count)