Merge commit 'release-4-0-0alpha15' into master4-tmp
[obnox/samba/samba-obnox.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.environ['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.environ["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
50 import dns.exception
51
52 default_ttl = 900
53 am_rodc = False
54 error_count = 0
55
56 parser = optparse.OptionParser("samba_dnsupdate")
57 sambaopts = options.SambaOptions(parser)
58 parser.add_option_group(sambaopts)
59 parser.add_option_group(options.VersionOptions(parser))
60 parser.add_option("--verbose", action="store_true")
61 parser.add_option("--all-names", action="store_true")
62 parser.add_option("--all-interfaces", action="store_true")
63 parser.add_option("--use-file", type="string", help="Use a file, rather than real DNS calls")
64 parser.add_option("--update-list", type="string", help="Add DNS names from the given file")
65 parser.add_option("--fail-immediately", action='store_true', help="Exit on first failure")
66
67 creds = None
68 ccachename = None
69
70 opts, args = parser.parse_args()
71
72 if len(args) != 0:
73     parser.print_usage()
74     sys.exit(1)
75
76 lp = sambaopts.get_loadparm()
77
78 domain = lp.get("realm")
79 host = lp.get("netbios name")
80 if opts.all_interfaces:
81     all_interfaces = True
82 else:
83     all_interfaces = False
84
85 IPs = samba.interface_ips(lp, all_interfaces)
86 nsupdate_cmd = lp.get('nsupdate command')
87
88 if len(IPs) == 0:
89     print "No IP interfaces - skipping DNS updates"
90     sys.exit(0)
91
92 IP6s = []
93 IP4s = []
94 for i in IPs:
95     if i.find(':') != -1:
96         if i.find('%') == -1:
97             # we don't want link local addresses for DNS updates
98             IP6s.append(i)
99     else:
100         IP4s.append(i)
101
102
103 if opts.verbose:
104     print "IPs: %s" % IPs
105
106 ########################################################
107 # get credentials if we haven't got them already
108 def get_credentials(lp):
109     from samba import credentials
110     global ccachename, creds
111     if creds is not None:
112         return
113     creds = credentials.Credentials()
114     creds.guess(lp)
115     creds.set_machine_account(lp)
116     creds.set_krb_forwardable(credentials.NO_KRB_FORWARDABLE)
117     (tmp_fd, ccachename) = tempfile.mkstemp()
118     creds.get_named_ccache(lp, ccachename)
119
120
121 #############################################
122 # an object to hold a parsed DNS line
123 class dnsobj(object):
124     def __init__(self, string_form):
125         list = string_form.split()
126         self.dest = None
127         self.port = None
128         self.ip = None
129         self.existing_port = None
130         self.existing_weight = None
131         self.type = list[0]
132         self.name = list[1].lower()
133         if self.type == 'SRV':
134             self.dest = list[2].lower()
135             self.port = list[3]
136         elif self.type in ['A', 'AAAA']:
137             self.ip   = list[2] # usually $IP, which gets replaced
138         elif self.type == 'CNAME':
139             self.dest = list[2].lower()
140         else:
141             print "Received unexpected DNS reply of type %s" % self.type
142             raise
143
144     def __str__(self):
145         if d.type == "A":     return "%s %s %s" % (self.type, self.name, self.ip)
146         if d.type == "AAAA":  return "%s %s %s" % (self.type, self.name, self.ip)
147         if d.type == "SRV":   return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
148         if d.type == "CNAME": return "%s %s %s" % (self.type, self.name, self.dest)
149
150
151 ################################################
152 # parse a DNS line from
153 def parse_dns_line(line, sub_vars):
154     subline = samba.substitute_var(line, sub_vars)
155     d = dnsobj(subline)
156     return d
157
158 ############################################
159 # see if two hostnames match
160 def hostname_match(h1, h2):
161     h1 = str(h1)
162     h2 = str(h2)
163     return h1.lower().rstrip('.') == h2.lower().rstrip('.')
164
165
166 ############################################
167 # check that a DNS entry exists
168 def check_dns_name(d):
169     normalised_name = d.name.rstrip('.') + '.'
170     if opts.verbose:
171         print "Looking for DNS entry %s as %s" % (d, normalised_name)
172  
173     if opts.use_file is not None:
174         try:
175             dns_file = open(opts.use_file, "r")
176         except IOError:
177             return False
178         
179         for line in dns_file:
180             line = line.strip()
181             if line == '' or line[0] == "#":
182                 continue
183             if line.lower() == str(d).lower():
184                 return True
185         return False
186
187     try:
188         ans = dns.resolver.query(normalised_name, d.type)
189     except dns.exception.DNSException:
190         if opts.verbose:
191             print "Failed to find DNS entry %s" % d
192         return False
193     if d.type in ['A', 'AAAA']:
194         # we need to be sure that our IP is there
195         for rdata in ans:
196             if str(rdata) == str(d.ip):
197                 return True
198     if d.type == 'CNAME':
199         for i in range(len(ans)):
200             if hostname_match(ans[i].target, d.dest):
201                 return True
202     if d.type == 'SRV':
203         for rdata in ans:
204             if opts.verbose:
205                 print "Checking %s against %s" % (rdata, d)
206             if hostname_match(rdata.target, d.dest):
207                 if str(rdata.port) == str(d.port):
208                     return True
209                 else:
210                     d.existing_port     = str(rdata.port)
211                     d.existing_weight = str(rdata.weight)
212
213     if opts.verbose:
214         print "Failed to find matching DNS entry %s" % d
215
216     return False
217
218
219 ###########################################
220 # get the list of substitution vars
221 def get_subst_vars():
222     global lp, am_rodc
223     vars = {}
224
225     samdb = SamDB(url=lp.samdb_url(), session_info=system_session(),
226                   lp=lp)
227
228     vars['DNSDOMAIN'] = lp.get('realm').lower()
229     vars['DNSFOREST'] = lp.get('realm').lower()
230     vars['HOSTNAME']  = lp.get('netbios name').lower() + "." + vars['DNSDOMAIN']
231     vars['NTDSGUID']  = samdb.get_ntds_GUID()
232     vars['SITE']      = samdb.server_site_name()
233     res = samdb.search(base=None, scope=SCOPE_BASE, attrs=["objectGUID"])
234     guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
235     vars['DOMAINGUID'] = guid
236     am_rodc = samdb.am_rodc()
237
238     return vars
239
240
241 ############################################
242 # call nsupdate for an entry
243 def call_nsupdate(d):
244     global ccachename, nsupdate_cmd
245
246     if opts.verbose:
247         print "Calling nsupdate for %s" % d
248
249     if opts.use_file is not None:
250         wfile = open(opts.use_file, 'a')
251         fcntl.lockf(wfile, fcntl.LOCK_EX)
252         wfile.write(str(d)+"\n")
253         fcntl.lockf(wfile, fcntl.LOCK_UN)
254         return
255
256     normalised_name = d.name.rstrip('.') + '.'
257
258     (tmp_fd, tmpfile) = tempfile.mkstemp()
259     f = os.fdopen(tmp_fd, 'w')
260     if d.type == "A":
261         f.write("update add %s %u A %s\n" % (normalised_name, default_ttl, d.ip))
262     if d.type == "AAAA":
263         f.write("update add %s %u AAAA %s\n" % (normalised_name, default_ttl, d.ip))
264     if d.type == "SRV":
265         if d.existing_port is not None:
266             f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
267                                                            d.existing_port, d.dest))
268         f.write("update add %s %u SRV 0 100 %s %s\n" % (normalised_name, default_ttl, d.port, d.dest))
269     if d.type == "CNAME":
270         f.write("update add %s %u CNAME %s\n" % (normalised_name, default_ttl, d.dest))
271     if opts.verbose:
272         f.write("show\n")
273     f.write("send\n")
274     f.close()
275
276     global error_count
277     os.environ["KRB5CCNAME"] = ccachename
278     try:
279         cmd = nsupdate_cmd[:]
280         cmd.append(tmpfile)
281         ret = subprocess.call(cmd, shell=False, env={"KRB5CCNAME": ccachename})
282         if ret != 0:
283             if opts.fail_immediately:
284                 sys.exit(1)
285             error_count = error_count + 1
286             if opts.verbose:
287                 print("Failed nsupdate: %d" % ret)
288     except Exception, estr:
289         if opts.fail_immediately:
290             sys.exit(1)
291         error_count = error_count + 1
292         if opts.verbose:
293             print("Failed nsupdate: %s : %s" % (str(d), estr))
294     os.unlink(tmpfile)
295
296
297
298 def rodc_dns_update(d, t):
299     '''a single DNS update via the RODC netlogon call'''
300     global sub_vars
301
302     if opts.verbose:
303         print "Calling netlogon RODC update for %s" % d
304
305     typemap = {
306         netlogon.NlDnsLdapAtSite       : netlogon.NlDnsInfoTypeNone,
307         netlogon.NlDnsGcAtSite         : netlogon.NlDnsDomainNameAlias,
308         netlogon.NlDnsDsaCname         : netlogon.NlDnsDomainNameAlias,
309         netlogon.NlDnsKdcAtSite        : netlogon.NlDnsInfoTypeNone,
310         netlogon.NlDnsDcAtSite         : netlogon.NlDnsInfoTypeNone,
311         netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
312         netlogon.NlDnsGenericGcAtSite  : netlogon.NlDnsDomainNameAlias
313         }
314
315     w = winbind.winbind("irpc:winbind_server", lp)
316     dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
317     dns_names.count = 1
318     name = netlogon.NL_DNS_NAME_INFO()
319     name.type = t
320     name.dns_domain_info_type = typemap[t]
321     name.priority = 0
322     name.weight   = 0
323     if d.port is not None:
324         name.port = int(d.port)
325     name.dns_register = True
326     dns_names.names = [ name ]
327     site_name = sub_vars['SITE'].decode('utf-8')
328
329     global error_count
330
331     try:
332         ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
333         if ret_names.names[0].status != 0:
334             print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
335             error_count = error_count + 1
336     except RuntimeError, reason:
337         print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
338         error_count = error_count + 1
339
340     if error_count != 0 and opts.fail_immediately:
341         sys.exit(1)
342
343
344 def call_rodc_update(d):
345     '''RODCs need to use the netlogon API for nsupdate'''
346     global lp, sub_vars
347
348     # we expect failure for 3268 if we aren't a GC
349     if d.port is not None and int(d.port) == 3268:
350         return
351
352     # map the DNS request to a netlogon update type
353     map = {
354         netlogon.NlDnsLdapAtSite       : '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
355         netlogon.NlDnsGcAtSite         : '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
356         netlogon.NlDnsDsaCname         : '${NTDSGUID}._msdcs.${DNSFOREST}',
357         netlogon.NlDnsKdcAtSite        : '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
358         netlogon.NlDnsDcAtSite         : '_ldap._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
359         netlogon.NlDnsRfc1510KdcAtSite : '_kerberos._tcp.${SITE}._sites.${DNSDOMAIN}',
360         netlogon.NlDnsGenericGcAtSite  : '_gc._tcp.${SITE}._sites.${DNSFOREST}'
361         }
362
363     for t in map:
364         subname = samba.substitute_var(map[t], sub_vars)
365         if subname.lower() == d.name.lower():
366             # found a match - do the update
367             rodc_dns_update(d, t)
368             return
369     if opts.verbose:
370         print("Unable to map to netlogon DNS update: %s" % d)
371
372
373 # get the list of DNS entries we should have
374 if opts.update_list:
375     dns_update_list = opts.update_list
376 else:
377     dns_update_list = lp.private_path('dns_update_list')
378
379 # use our private krb5.conf to avoid problems with the wrong domain
380 # bind9 nsupdate wants the default domain set
381 krb5conf = lp.private_path('krb5.conf')
382 os.environ['KRB5_CONFIG'] = krb5conf
383
384 file = open(dns_update_list, "r")
385
386 # get the substitution dictionary
387 sub_vars = get_subst_vars()
388
389 # build up a list of update commands to pass to nsupdate
390 update_list = []
391 dns_list = []
392
393 # read each line, and check that the DNS name exists
394 for line in file:
395     line = line.strip()
396     if line == '' or line[0] == "#":
397         continue
398     d = parse_dns_line(line, sub_vars)
399     if d.type == 'A' and len(IP4s) == 0:
400         continue
401     if d.type == 'AAAA' and len(IP6s) == 0:
402         continue
403     dns_list.append(d)
404
405 # now expand the entries, if any are A record with ip set to $IP
406 # then replace with multiple entries, one for each interface IP
407 for d in dns_list:
408     if d.ip != "$IP":
409         continue
410     if d.type == 'A':
411         d.ip = IP4s[0]
412         for i in range(len(IP4s)-1):
413             d2 = dnsobj(str(d))
414             d2.ip = IP4s[i+1]
415             dns_list.append(d2)
416     if d.type == 'AAAA':
417         d.ip = IP6s[0]
418         for i in range(len(IP6s)-1):
419             d2 = dnsobj(str(d))
420             d2.ip = IP6s[i+1]
421             dns_list.append(d2)
422
423 # now check if the entries already exist on the DNS server
424 for d in dns_list:
425     if opts.all_names or not check_dns_name(d):
426         update_list.append(d)
427
428 if len(update_list) == 0:
429     if opts.verbose:
430         print "No DNS updates needed"
431     sys.exit(0)
432
433 # get our krb5 creds
434 get_credentials(lp)
435
436 # ask nsupdate to add entries as needed
437 for d in update_list:
438     if am_rodc:
439         if d.name.lower() == domain.lower():
440             continue
441         if not d.type in [ 'A', 'AAAA' ]:
442             call_rodc_update(d)
443         else:
444             call_nsupdate(d)
445     else:
446         call_nsupdate(d)
447
448 # delete the ccache if we created it
449 if ccachename is not None:
450     os.unlink(ccachename)
451
452 if error_count != 0:
453     print("Failed update of %u entries" % error_count)
454 sys.exit(error_count)