samba_dnsupdate: Allow the tool to work in 'make test'.
[obnox/samba/samba-obnox.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 import dsdb
46 from samba.auth import system_session
47 from samba.samdb import SamDB
48 from samba.dcerpc import netlogon, winbind
49
50 samba.ensure_third_party_module("dns", "dnspython")
51 import dns.resolver
52 import dns.exception
53
54 default_ttl = 900
55 am_rodc = False
56 error_count = 0
57
58 parser = optparse.OptionParser("samba_dnsupdate")
59 sambaopts = options.SambaOptions(parser)
60 parser.add_option_group(sambaopts)
61 parser.add_option_group(options.VersionOptions(parser))
62 parser.add_option("--verbose", action="store_true")
63 parser.add_option("--all-names", action="store_true")
64 parser.add_option("--all-interfaces", action="store_true")
65 parser.add_option("--use-file", type="string", help="Use a file, rather than real DNS calls")
66 parser.add_option("--update-list", type="string", help="Add DNS names from the given file")
67 parser.add_option("--update-cache", type="string", help="Cache database of already registered records")
68 parser.add_option("--fail-immediately", action='store_true', help="Exit on first failure")
69 parser.add_option("--no-credentials", dest='nocreds', action='store_true', help="don't try and get credentials")
70 parser.add_option("--no-substiutions", dest='nosubs', action='store_true', help="don't try and expands variables in file specified by --update-list")
71
72 creds = None
73 ccachename = None
74
75 opts, args = parser.parse_args()
76
77 if len(args) != 0:
78     parser.print_usage()
79     sys.exit(1)
80
81 lp = sambaopts.get_loadparm()
82
83 domain = lp.get("realm")
84 host = lp.get("netbios name")
85 if opts.all_interfaces:
86     all_interfaces = True
87 else:
88     all_interfaces = False
89
90 IPs = samba.interface_ips(lp, all_interfaces)
91 nsupdate_cmd = lp.get('nsupdate command')
92
93 if len(IPs) == 0:
94     print "No IP interfaces - skipping DNS updates"
95     sys.exit(0)
96
97 IP6s = []
98 IP4s = []
99 for i in IPs:
100     if i.find(':') != -1:
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     try:
122         creds.get_named_ccache(lp, ccachename)
123     except RuntimeError as e:
124         os.unlink(ccachename)
125         raise e
126
127
128 class dnsobj(object):
129     """an object to hold a parsed DNS line"""
130
131     def __init__(self, string_form):
132         list = string_form.split()
133         if len(list) < 3:
134             raise Exception("Invalid DNS entry %r" % string_form)
135         self.dest = None
136         self.port = None
137         self.ip = None
138         self.existing_port = None
139         self.existing_weight = None
140         self.type = list[0]
141         self.name = list[1]
142         self.nameservers = []
143         if self.type == 'SRV':
144             if len(list) < 4:
145                 raise Exception("Invalid DNS entry %r" % string_form)
146             self.dest = list[2]
147             self.port = list[3]
148         elif self.type in ['A', 'AAAA']:
149             self.ip   = list[2] # usually $IP, which gets replaced
150         elif self.type == 'CNAME':
151             self.dest = list[2]
152         elif self.type == 'NS':
153             self.dest = list[2]
154         else:
155             raise Exception("Received unexpected DNS reply of type %s: %s" % (self.type, string_form))
156
157     def __str__(self):
158         if self.type == "A":
159             return "%s %s %s" % (self.type, self.name, self.ip)
160         if self.type == "AAAA":
161             return "%s %s %s" % (self.type, self.name, self.ip)
162         if self.type == "SRV":
163             return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
164         if self.type == "CNAME":
165             return "%s %s %s" % (self.type, self.name, self.dest)
166         if self.type == "NS":
167             return "%s %s %s" % (self.type, self.name, self.dest)
168
169
170 def parse_dns_line(line, sub_vars):
171     """parse a DNS line from."""
172     if line.startswith("SRV _ldap._tcp.pdc._msdcs.") and not samdb.am_pdc():
173         # We keep this as compat to the dns_update_list of 4.0/4.1
174         if opts.verbose:
175             print "Skipping PDC entry (%s) as we are not a PDC" % line
176         return None
177     subline = samba.substitute_var(line, sub_vars)
178     if subline == '' or subline[0] == "#":
179         return None
180     return dnsobj(subline)
181
182
183 def hostname_match(h1, h2):
184     """see if two hostnames match."""
185     h1 = str(h1)
186     h2 = str(h2)
187     return h1.lower().rstrip('.') == h2.lower().rstrip('.')
188
189
190 def check_dns_name(d):
191     """check that a DNS entry exists."""
192     normalised_name = d.name.rstrip('.') + '.'
193     if opts.verbose:
194         print "Looking for DNS entry %s as %s" % (d, normalised_name)
195
196     if opts.use_file is not None:
197         try:
198             dns_file = open(opts.use_file, "r")
199         except IOError:
200             return False
201
202         for line in dns_file:
203             line = line.strip()
204             if line == '' or line[0] == "#":
205                 continue
206             if line.lower() == str(d).lower():
207                 return True
208         return False
209
210     resolv_conf = os.getenv('RESOLV_WRAPPER_CONF')
211     if not resolv_conf:
212         resolv_conf = '/etc/resolv.conf'
213     resolver = dns.resolver.Resolver(filename=resolv_conf, configure=True)
214
215     if d.nameservers != []:
216         resolver.nameservers = d.nameservers
217     else:
218         d.nameservers = resolver.nameservers
219
220     try:
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
270     vars['IF_DC'] = ""
271     vars['IF_RWDC'] = "# "
272     vars['IF_RODC'] = "# "
273     vars['IF_PDC'] = "# "
274     vars['IF_GC'] = "# "
275     vars['IF_RWGC'] = "# "
276     vars['IF_ROGC'] = "# "
277     vars['IF_DNS_DOMAIN'] = "# "
278     vars['IF_RWDNS_DOMAIN'] = "# "
279     vars['IF_RODNS_DOMAIN'] = "# "
280     vars['IF_DNS_FOREST'] = "# "
281     vars['IF_RWDNS_FOREST'] = "# "
282     vars['IF_R0DNS_FOREST'] = "# "
283
284     am_rodc = samdb.am_rodc()
285     if am_rodc:
286         vars['IF_RODC'] = ""
287     else:
288         vars['IF_RWDC'] = ""
289
290     if samdb.am_pdc():
291         vars['IF_PDC'] = ""
292
293     # check if we "are DNS server"
294     res = samdb.search(base=samdb.get_config_basedn(),
295                    expression='(objectguid=%s)' % vars['NTDSGUID'],
296                    attrs=["options", "msDS-hasMasterNCs"])
297
298     if len(res) == 1:
299         if "options" in res[0]:
300             options = int(res[0]["options"][0])
301             if (options & dsdb.DS_NTDSDSA_OPT_IS_GC) != 0:
302                 vars['IF_GC'] = ""
303                 if am_rodc:
304                     vars['IF_ROGC'] = ""
305                 else:
306                     vars['IF_RWGC'] = ""
307
308         basedn = str(samdb.get_default_basedn())
309         forestdn = str(samdb.get_root_basedn())
310
311         if "msDS-hasMasterNCs" in res[0]:
312             for e in res[0]["msDS-hasMasterNCs"]:
313                 if str(e) == "DC=DomainDnsZones,%s" % basedn:
314                     vars['IF_DNS_DOMAIN'] = ""
315                     if am_rodc:
316                         vars['IF_RODNS_DOMAIN'] = ""
317                     else:
318                         vars['IF_RWDNS_DOMAIN'] = ""
319                 if str(e) == "DC=ForestDnsZones,%s" % forestdn:
320                     vars['IF_DNS_FOREST'] = ""
321                     if am_rodc:
322                         vars['IF_RODNS_FOREST'] = ""
323                     else:
324                         vars['IF_RWDNS_FOREST'] = ""
325
326     return vars
327
328
329 def call_nsupdate(d, op="add"):
330     """call nsupdate for an entry."""
331     global ccachename, nsupdate_cmd, krb5conf
332
333     assert(op in ["add", "delete"])
334
335     if opts.verbose:
336         print "Calling nsupdate for %s (%s)" % (d, op)
337
338     if opts.use_file is not None:
339         try:
340             rfile = open(opts.use_file, 'r+')
341         except IOError:
342             # Perhaps create it
343             rfile = open(opts.use_file, 'w+')
344             # Open it for reading again, in case someone else got to it first
345             rfile = open(opts.use_file, 'r+')
346         fcntl.lockf(rfile, fcntl.LOCK_EX)
347         (file_dir, file_name) = os.path.split(opts.use_file)
348         (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
349         wfile = os.fdopen(tmp_fd, 'a')
350         rfile.seek(0)
351         for line in rfile:
352             if op == "delete":
353                 l = parse_dns_line(line, {})
354                 if str(l).lower() == str(d).lower():
355                     continue
356             wfile.write(line)
357         if op == "add":
358             wfile.write(str(d)+"\n")
359         os.rename(tmpfile, opts.use_file)
360         fcntl.lockf(rfile, fcntl.LOCK_UN)
361         return
362
363     normalised_name = d.name.rstrip('.') + '.'
364
365     (tmp_fd, tmpfile) = tempfile.mkstemp()
366     f = os.fdopen(tmp_fd, 'w')
367     if d.nameservers != []:
368         f.write('server %s\n' % d.nameservers[0])
369     if d.type == "A":
370         f.write("update %s %s %u A %s\n" % (op, normalised_name, default_ttl, d.ip))
371     if d.type == "AAAA":
372         f.write("update %s %s %u AAAA %s\n" % (op, normalised_name, default_ttl, d.ip))
373     if d.type == "SRV":
374         if op == "add" and d.existing_port is not None:
375             f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
376                                                            d.existing_port, d.dest))
377         f.write("update %s %s %u SRV 0 100 %s %s\n" % (op, normalised_name, default_ttl, d.port, d.dest))
378     if d.type == "CNAME":
379         f.write("update %s %s %u CNAME %s\n" % (op, normalised_name, default_ttl, d.dest))
380     if d.type == "NS":
381         f.write("update %s %s %u NS %s\n" % (op, normalised_name, default_ttl, d.dest))
382     if opts.verbose:
383         f.write("show\n")
384     f.write("send\n")
385     f.close()
386
387     global error_count
388     if ccachename:
389         os.environ["KRB5CCNAME"] = ccachename
390     try:
391         cmd = nsupdate_cmd[:]
392         cmd.append(tmpfile)
393         env = os.environ
394         if krb5conf:
395             env["KRB5_CONFIG"] = krb5conf
396         if ccachename:
397             env["KRB5CCNAME"] = ccachename
398         ret = subprocess.call(cmd, shell=False, env=env)
399         if ret != 0:
400             if opts.fail_immediately:
401                 if opts.verbose:
402                     print("Failed update with %s" % tmpfile)
403                 sys.exit(1)
404             error_count = error_count + 1
405             if opts.verbose:
406                 print("Failed nsupdate: %d" % ret)
407     except Exception, estr:
408         if opts.fail_immediately:
409             sys.exit(1)
410         error_count = error_count + 1
411         if opts.verbose:
412             print("Failed nsupdate: %s : %s" % (str(d), estr))
413     os.unlink(tmpfile)
414
415
416
417 def rodc_dns_update(d, t, op):
418     '''a single DNS update via the RODC netlogon call'''
419     global sub_vars
420
421     assert(op in ["add", "delete"])
422
423     if opts.verbose:
424         print "Calling netlogon RODC update for %s" % d
425
426     typemap = {
427         netlogon.NlDnsLdapAtSite       : netlogon.NlDnsInfoTypeNone,
428         netlogon.NlDnsGcAtSite         : netlogon.NlDnsDomainNameAlias,
429         netlogon.NlDnsDsaCname         : netlogon.NlDnsDomainNameAlias,
430         netlogon.NlDnsKdcAtSite        : netlogon.NlDnsInfoTypeNone,
431         netlogon.NlDnsDcAtSite         : netlogon.NlDnsInfoTypeNone,
432         netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
433         netlogon.NlDnsGenericGcAtSite  : netlogon.NlDnsDomainNameAlias
434         }
435
436     w = winbind.winbind("irpc:winbind_server", lp)
437     dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
438     dns_names.count = 1
439     name = netlogon.NL_DNS_NAME_INFO()
440     name.type = t
441     name.dns_domain_info_type = typemap[t]
442     name.priority = 0
443     name.weight   = 0
444     if d.port is not None:
445         name.port = int(d.port)
446     if op == "add":
447         name.dns_register = True
448     else:
449         name.dns_register = False
450     dns_names.names = [ name ]
451     site_name = sub_vars['SITE'].decode('utf-8')
452
453     global error_count
454
455     try:
456         ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
457         if ret_names.names[0].status != 0:
458             print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
459             error_count = error_count + 1
460     except RuntimeError, reason:
461         print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
462         error_count = error_count + 1
463
464     if error_count != 0 and opts.fail_immediately:
465         sys.exit(1)
466
467
468 def call_rodc_update(d, op="add"):
469     '''RODCs need to use the netlogon API for nsupdate'''
470     global lp, sub_vars
471
472     assert(op in ["add", "delete"])
473
474     # we expect failure for 3268 if we aren't a GC
475     if d.port is not None and int(d.port) == 3268:
476         return
477
478     # map the DNS request to a netlogon update type
479     map = {
480         netlogon.NlDnsLdapAtSite       : '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
481         netlogon.NlDnsGcAtSite         : '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
482         netlogon.NlDnsDsaCname         : '${NTDSGUID}._msdcs.${DNSFOREST}',
483         netlogon.NlDnsKdcAtSite        : '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
484         netlogon.NlDnsDcAtSite         : '_ldap._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
485         netlogon.NlDnsRfc1510KdcAtSite : '_kerberos._tcp.${SITE}._sites.${DNSDOMAIN}',
486         netlogon.NlDnsGenericGcAtSite  : '_gc._tcp.${SITE}._sites.${DNSFOREST}'
487         }
488
489     for t in map:
490         subname = samba.substitute_var(map[t], sub_vars)
491         if subname.lower() == d.name.lower():
492             # found a match - do the update
493             rodc_dns_update(d, t, op)
494             return
495     if opts.verbose:
496         print("Unable to map to netlogon DNS update: %s" % d)
497
498
499 # get the list of DNS entries we should have
500 if opts.update_list:
501     dns_update_list = opts.update_list
502 else:
503     dns_update_list = lp.private_path('dns_update_list')
504
505 if opts.update_cache:
506     dns_update_cache = opts.update_cache
507 else:
508     dns_update_cache = lp.private_path('dns_update_cache')
509
510 # use our private krb5.conf to avoid problems with the wrong domain
511 # bind9 nsupdate wants the default domain set
512 krb5conf = lp.private_path('krb5.conf')
513 os.environ['KRB5_CONFIG'] = krb5conf
514
515 file = open(dns_update_list, "r")
516
517 if opts.nosubs:
518     sub_vars = {}
519 else:
520     samdb = SamDB(url=lp.samdb_url(), session_info=system_session(), lp=lp)
521
522     # get the substitution dictionary
523     sub_vars = get_subst_vars(samdb)
524
525 # build up a list of update commands to pass to nsupdate
526 update_list = []
527 dns_list = []
528 cache_list = []
529 delete_list = []
530
531 dup_set = set()
532 cache_set = set()
533
534 rebuild_cache = False
535 try:
536     cfile = open(dns_update_cache, 'r+')
537 except IOError:
538     # Perhaps create it
539     cfile = open(dns_update_cache, 'w+')
540     # Open it for reading again, in case someone else got to it first
541     cfile = open(dns_update_cache, 'r+')
542 fcntl.lockf(cfile, fcntl.LOCK_EX)
543 for line in cfile:
544     line = line.strip()
545     if line == '' or line[0] == "#":
546         continue
547     c = parse_dns_line(line, {})
548     if c is None:
549         continue
550     if str(c) not in cache_set:
551         cache_list.append(c)
552         cache_set.add(str(c))
553
554 # read each line, and check that the DNS name exists
555 for line in file:
556     line = line.strip()
557     if line == '' or line[0] == "#":
558         continue
559     d = parse_dns_line(line, sub_vars)
560     if d is None:
561         continue
562     if d.type == 'A' and len(IP4s) == 0:
563         continue
564     if d.type == 'AAAA' and len(IP6s) == 0:
565         continue
566     if str(d) not in dup_set:
567         dns_list.append(d)
568         dup_set.add(str(d))
569
570 # now expand the entries, if any are A record with ip set to $IP
571 # then replace with multiple entries, one for each interface IP
572 for d in dns_list:
573     if d.ip != "$IP":
574         continue
575     if d.type == 'A':
576         d.ip = IP4s[0]
577         for i in range(len(IP4s)-1):
578             d2 = dnsobj(str(d))
579             d2.ip = IP4s[i+1]
580             dns_list.append(d2)
581     if d.type == 'AAAA':
582         d.ip = IP6s[0]
583         for i in range(len(IP6s)-1):
584             d2 = dnsobj(str(d))
585             d2.ip = IP6s[i+1]
586             dns_list.append(d2)
587
588 # now check if the entries already exist on the DNS server
589 for d in dns_list:
590     found = False
591     for c in cache_list:
592         if str(c).lower() == str(d).lower():
593             found = True
594             break
595     if not found:
596         rebuild_cache = True
597     if opts.all_names or not check_dns_name(d):
598         update_list.append(d)
599
600 for c in cache_list:
601     found = False
602     for d in dns_list:
603         if str(c).lower() == str(d).lower():
604             found = True
605             break
606     if found:
607         continue
608     rebuild_cache = True
609     if not opts.all_names and not check_dns_name(c):
610         continue
611     delete_list.append(c)
612
613 if len(delete_list) == 0 and len(update_list) == 0 and not rebuild_cache:
614     if opts.verbose:
615         print "No DNS updates needed"
616     sys.exit(0)
617
618 # get our krb5 creds
619 if len(delete_list) != 0 or len(update_list) != 0:
620     if not opts.nocreds:
621         get_credentials(lp)
622
623 # ask nsupdate to delete entries as needed
624 for d in delete_list:
625     if am_rodc:
626         if d.name.lower() == domain.lower():
627             continue
628         if not d.type in [ 'A', 'AAAA' ]:
629             call_rodc_update(d, op="delete")
630         else:
631             call_nsupdate(d, op="delete")
632     else:
633         call_nsupdate(d, op="delete")
634
635 # ask nsupdate to add entries as needed
636 for d in update_list:
637     if am_rodc:
638         if d.name.lower() == domain.lower():
639             continue
640         if not d.type in [ 'A', 'AAAA' ]:
641             call_rodc_update(d)
642         else:
643             call_nsupdate(d)
644     else:
645         call_nsupdate(d)
646
647 if rebuild_cache:
648     (file_dir, file_name) = os.path.split(dns_update_cache)
649     (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
650     wfile = os.fdopen(tmp_fd, 'a')
651     for d in dns_list:
652         wfile.write(str(d)+"\n")
653     os.rename(tmpfile, dns_update_cache)
654 fcntl.lockf(cfile, fcntl.LOCK_UN)
655
656 # delete the ccache if we created it
657 if ccachename is not None:
658     os.unlink(ccachename)
659
660 if error_count != 0:
661     print("Failed update of %u entries" % error_count)
662 sys.exit(error_count)