source4/scripting: add an option to samba_dnsupdate to add ns records.
[metze/samba/wip.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 from samba.netcmd.dns import cmd_dns
50 from samba import gensec
51
52 samba.ensure_third_party_module("dns", "dnspython")
53 import dns.resolver
54 import dns.exception
55
56 default_ttl = 900
57 am_rodc = False
58 error_count = 0
59
60 parser = optparse.OptionParser("samba_dnsupdate")
61 sambaopts = options.SambaOptions(parser)
62 parser.add_option_group(sambaopts)
63 parser.add_option_group(options.VersionOptions(parser))
64 parser.add_option("--verbose", action="store_true")
65 parser.add_option("--use-samba-tool", action="store_true", help="Use samba-tool to make updates over RPC, rather than over DNS")
66 parser.add_option("--use-nsupdate", action="store_true", help="Use nsupdate command to make updates over DNS (default, if kinit successful)")
67 parser.add_option("--all-names", action="store_true")
68 parser.add_option("--all-interfaces", action="store_true")
69 parser.add_option("--current-ip", action="append", help="IP address to update DNS to match (helpful if behind NAT, valid multiple times, defaults to values from interfaces=)")
70 parser.add_option("--rpc-server-ip", type="string", help="IP address of server to use with samba-tool (defaults to first --current-ip)")
71 parser.add_option("--use-file", type="string", help="Use a file, rather than real DNS calls")
72 parser.add_option("--add-ns", action="store_true", help="Add an NS record to the DNS file for self-tests. Can only be used with --use-file")
73 parser.add_option("--update-list", type="string", help="Add DNS names from the given file")
74 parser.add_option("--update-cache", type="string", help="Cache database of already registered records")
75 parser.add_option("--fail-immediately", action='store_true', help="Exit on first failure")
76 parser.add_option("--no-credentials", dest='nocreds', action='store_true', help="don't try and get credentials")
77 parser.add_option("--no-substitutions", dest='nosubs', action='store_true', help="don't try and expands variables in file specified by --update-list")
78
79 creds = None
80 ccachename = None
81
82 opts, args = parser.parse_args()
83
84 if len(args) != 0:
85     parser.print_usage()
86     sys.exit(1)
87
88 lp = sambaopts.get_loadparm()
89
90 domain = lp.get("realm")
91 host = lp.get("netbios name")
92 if opts.all_interfaces:
93     all_interfaces = True
94 else:
95     all_interfaces = False
96
97 if opts.current_ip:
98     IPs = opts.current_ip
99 else:
100     IPs = samba.interface_ips(lp, all_interfaces)
101
102 nsupdate_cmd = lp.get('nsupdate command')
103
104 if len(IPs) == 0:
105     print "No IP interfaces - skipping DNS updates"
106     sys.exit(0)
107
108 if opts.rpc_server_ip:
109     rpc_server_ip = opts.rpc_server_ip
110 else:
111     rpc_server_ip = IPs[0]
112
113 IP6s = []
114 IP4s = []
115 for i in IPs:
116     if i.find(':') != -1:
117         IP6s.append(i)
118     else:
119         IP4s.append(i)
120
121
122 if opts.verbose:
123     print "IPs: %s" % IPs
124
125
126 def get_credentials(lp):
127     """# get credentials if we haven't got them already."""
128     from samba import credentials
129     global ccachename
130     creds = credentials.Credentials()
131     creds.guess(lp)
132     creds.set_machine_account(lp)
133     creds.set_krb_forwardable(credentials.NO_KRB_FORWARDABLE)
134     (tmp_fd, ccachename) = tempfile.mkstemp()
135     try:
136         creds.get_named_ccache(lp, ccachename)
137
138         if opts.use_file is not None:
139             return
140
141         # Now confirm we can get a ticket to a DNS server
142         ans = check_one_dns_name(sub_vars['DNSDOMAIN'] + '.', 'NS')
143         for i in range(len(ans)):
144             target_hostname = str(ans[i].target).rstrip('.')
145             settings = {}
146             settings["lp_ctx"] = lp
147             settings["target_hostname"] = target_hostname
148
149             gensec_client = gensec.Security.start_client(settings)
150             gensec_client.set_credentials(creds)
151             gensec_client.set_target_service("DNS")
152             gensec_client.set_target_hostname(target_hostname)
153             gensec_client.want_feature(gensec.FEATURE_SEAL)
154             gensec_client.start_mech_by_sasl_name("GSSAPI")
155             server_to_client = ""
156             try:
157                 (client_finished, client_to_server) = gensec_client.update(server_to_client)
158                 if opts.verbose:
159                     print "Successfully obtained Kerberos ticket to DNS/%s as %s" \
160                             % (target_hostname, creds.get_username())
161                 return
162             except RuntimeError:
163                 # Only raise an exception if they all failed
164                 if i != len(ans) - 1:
165                     pass
166                 raise
167
168     except RuntimeError as e:
169         os.unlink(ccachename)
170         raise e
171
172
173 class dnsobj(object):
174     """an object to hold a parsed DNS line"""
175
176     def __init__(self, string_form):
177         list = string_form.split()
178         if len(list) < 3:
179             raise Exception("Invalid DNS entry %r" % string_form)
180         self.dest = None
181         self.port = None
182         self.ip = None
183         self.existing_port = None
184         self.existing_weight = None
185         self.existing_cname_target = None
186         self.rpc = False
187         self.zone = None
188         if list[0] == "RPC":
189             self.rpc = True
190             self.zone = list[1]
191             list = list[2:]
192         self.type = list[0]
193         self.name = list[1]
194         self.nameservers = []
195         if self.type == 'SRV':
196             if len(list) < 4:
197                 raise Exception("Invalid DNS entry %r" % string_form)
198             self.dest = list[2]
199             self.port = list[3]
200         elif self.type in ['A', 'AAAA']:
201             self.ip   = list[2] # usually $IP, which gets replaced
202         elif self.type == 'CNAME':
203             self.dest = list[2]
204         elif self.type == 'NS':
205             self.dest = list[2]
206         else:
207             raise Exception("Received unexpected DNS reply of type %s: %s" % (self.type, string_form))
208
209     def __str__(self):
210         if self.type == "A":
211             return "%s %s %s" % (self.type, self.name, self.ip)
212         if self.type == "AAAA":
213             return "%s %s %s" % (self.type, self.name, self.ip)
214         if self.type == "SRV":
215             return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
216         if self.type == "CNAME":
217             return "%s %s %s" % (self.type, self.name, self.dest)
218         if self.type == "NS":
219             return "%s %s %s" % (self.type, self.name, self.dest)
220
221
222 def parse_dns_line(line, sub_vars):
223     """parse a DNS line from."""
224     if line.startswith("SRV _ldap._tcp.pdc._msdcs.") and not samdb.am_pdc():
225         # We keep this as compat to the dns_update_list of 4.0/4.1
226         if opts.verbose:
227             print "Skipping PDC entry (%s) as we are not a PDC" % line
228         return None
229     subline = samba.substitute_var(line, sub_vars)
230     if subline == '' or subline[0] == "#":
231         return None
232     return dnsobj(subline)
233
234
235 def hostname_match(h1, h2):
236     """see if two hostnames match."""
237     h1 = str(h1)
238     h2 = str(h2)
239     return h1.lower().rstrip('.') == h2.lower().rstrip('.')
240
241 def check_one_dns_name(name, name_type, d=None):
242     resolv_conf = os.getenv('RESOLV_CONF')
243     if not resolv_conf:
244         resolv_conf = '/etc/resolv.conf'
245     resolver = dns.resolver.Resolver(filename=resolv_conf, configure=True)
246
247     if d is not None and d.nameservers != []:
248         resolver.nameservers = d.nameservers
249     elif d is not None:
250         d.nameservers = resolver.nameservers
251
252     ans = resolver.query(name, name_type)
253     return ans
254
255 def check_dns_name(d):
256     """check that a DNS entry exists."""
257     normalised_name = d.name.rstrip('.') + '.'
258     if opts.verbose:
259         print "Looking for DNS entry %s as %s" % (d, normalised_name)
260
261     if opts.use_file is not None:
262         try:
263             dns_file = open(opts.use_file, "r")
264         except IOError:
265             return False
266
267         for line in dns_file:
268             line = line.strip()
269             if line == '' or line[0] == "#":
270                 continue
271             if line.lower() == str(d).lower():
272                 return True
273         return False
274
275     try:
276         ans = check_one_dns_name(normalised_name, d.type, d)
277     except dns.exception.Timeout:
278         raise Exception("Timeout while waiting to contact a working DNS server while looking for %s as %s" % (d, normalised_name))
279     except dns.resolver.NoNameservers:
280         raise Exception("Unable to contact a working DNS server while looking for %s as %s" % (d, normalised_name))
281     except dns.resolver.NXDOMAIN:
282         if opts.verbose:
283             print "The DNS entry %s, queried as %s does not exist" % (d, normalised_name)
284         return False
285     except dns.resolver.NoAnswer:
286         if opts.verbose:
287             print "The DNS entry %s, queried as %s does not hold this record type" % (d, normalised_name)
288         return False
289     except dns.exception.DNSException:
290         raise Exception("Failure while trying to resolve %s as %s" % (d, normalised_name))
291     if d.type in ['A', 'AAAA']:
292         # we need to be sure that our IP is there
293         for rdata in ans:
294             if str(rdata) == str(d.ip):
295                 return True
296     elif d.type == 'CNAME':
297         for i in range(len(ans)):
298             if hostname_match(ans[i].target, d.dest):
299                 return True
300             else:
301                 d.existing_cname_target = str(ans[i].target)
302     elif d.type == 'NS':
303         for i in range(len(ans)):
304             if hostname_match(ans[i].target, d.dest):
305                 return True
306     elif d.type == 'SRV':
307         for rdata in ans:
308             if opts.verbose:
309                 print "Checking %s against %s" % (rdata, d)
310             if hostname_match(rdata.target, d.dest):
311                 if str(rdata.port) == str(d.port):
312                     return True
313                 else:
314                     d.existing_port     = str(rdata.port)
315                     d.existing_weight = str(rdata.weight)
316
317     if opts.verbose:
318         print "Lookup of %s succeeded, but we failed to find a matching DNS entry for %s" % (normalised_name, d)
319
320     return False
321
322
323 def get_subst_vars(samdb):
324     """get the list of substitution vars."""
325     global lp, am_rodc
326     vars = {}
327
328     vars['DNSDOMAIN'] = samdb.domain_dns_name()
329     vars['DNSFOREST'] = samdb.forest_dns_name()
330     vars['HOSTNAME']  = samdb.host_dns_name()
331     vars['NTDSGUID']  = samdb.get_ntds_GUID()
332     vars['SITE']      = samdb.server_site_name()
333     res = samdb.search(base=samdb.get_default_basedn(), scope=SCOPE_BASE, attrs=["objectGUID"])
334     guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
335     vars['DOMAINGUID'] = guid
336
337     vars['IF_DC'] = ""
338     vars['IF_RWDC'] = "# "
339     vars['IF_RODC'] = "# "
340     vars['IF_PDC'] = "# "
341     vars['IF_GC'] = "# "
342     vars['IF_RWGC'] = "# "
343     vars['IF_ROGC'] = "# "
344     vars['IF_DNS_DOMAIN'] = "# "
345     vars['IF_RWDNS_DOMAIN'] = "# "
346     vars['IF_RODNS_DOMAIN'] = "# "
347     vars['IF_DNS_FOREST'] = "# "
348     vars['IF_RWDNS_FOREST'] = "# "
349     vars['IF_R0DNS_FOREST'] = "# "
350
351     am_rodc = samdb.am_rodc()
352     if am_rodc:
353         vars['IF_RODC'] = ""
354     else:
355         vars['IF_RWDC'] = ""
356
357     if samdb.am_pdc():
358         vars['IF_PDC'] = ""
359
360     # check if we "are DNS server"
361     res = samdb.search(base=samdb.get_config_basedn(),
362                    expression='(objectguid=%s)' % vars['NTDSGUID'],
363                    attrs=["options", "msDS-hasMasterNCs"])
364
365     if len(res) == 1:
366         if "options" in res[0]:
367             options = int(res[0]["options"][0])
368             if (options & dsdb.DS_NTDSDSA_OPT_IS_GC) != 0:
369                 vars['IF_GC'] = ""
370                 if am_rodc:
371                     vars['IF_ROGC'] = ""
372                 else:
373                     vars['IF_RWGC'] = ""
374
375         basedn = str(samdb.get_default_basedn())
376         forestdn = str(samdb.get_root_basedn())
377
378         if "msDS-hasMasterNCs" in res[0]:
379             for e in res[0]["msDS-hasMasterNCs"]:
380                 if str(e) == "DC=DomainDnsZones,%s" % basedn:
381                     vars['IF_DNS_DOMAIN'] = ""
382                     if am_rodc:
383                         vars['IF_RODNS_DOMAIN'] = ""
384                     else:
385                         vars['IF_RWDNS_DOMAIN'] = ""
386                 if str(e) == "DC=ForestDnsZones,%s" % forestdn:
387                     vars['IF_DNS_FOREST'] = ""
388                     if am_rodc:
389                         vars['IF_RODNS_FOREST'] = ""
390                     else:
391                         vars['IF_RWDNS_FOREST'] = ""
392
393     return vars
394
395
396 def call_nsupdate(d, op="add"):
397     """call nsupdate for an entry."""
398     global ccachename, nsupdate_cmd, krb5conf
399
400     assert(op in ["add", "delete"])
401
402     if opts.verbose:
403         print "Calling nsupdate for %s (%s)" % (d, op)
404
405     if opts.use_file is not None:
406         try:
407             rfile = open(opts.use_file, 'r+')
408         except IOError:
409             # Perhaps create it
410             rfile = open(opts.use_file, 'w+')
411             # Open it for reading again, in case someone else got to it first
412             rfile = open(opts.use_file, 'r+')
413         fcntl.lockf(rfile, fcntl.LOCK_EX)
414         (file_dir, file_name) = os.path.split(opts.use_file)
415         (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
416         wfile = os.fdopen(tmp_fd, 'a')
417         rfile.seek(0)
418         for line in rfile:
419             if op == "delete":
420                 l = parse_dns_line(line, {})
421                 if str(l).lower() == str(d).lower():
422                     continue
423             wfile.write(line)
424         if op == "add":
425             wfile.write(str(d)+"\n")
426         os.rename(tmpfile, opts.use_file)
427         fcntl.lockf(rfile, fcntl.LOCK_UN)
428         return
429
430     normalised_name = d.name.rstrip('.') + '.'
431
432     (tmp_fd, tmpfile) = tempfile.mkstemp()
433     f = os.fdopen(tmp_fd, 'w')
434     if d.nameservers != []:
435         f.write('server %s\n' % d.nameservers[0])
436     if d.type == "A":
437         f.write("update %s %s %u A %s\n" % (op, normalised_name, default_ttl, d.ip))
438     if d.type == "AAAA":
439         f.write("update %s %s %u AAAA %s\n" % (op, normalised_name, default_ttl, d.ip))
440     if d.type == "SRV":
441         if op == "add" and d.existing_port is not None:
442             f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
443                                                            d.existing_port, d.dest))
444         f.write("update %s %s %u SRV 0 100 %s %s\n" % (op, normalised_name, default_ttl, d.port, d.dest))
445     if d.type == "CNAME":
446         f.write("update %s %s %u CNAME %s\n" % (op, normalised_name, default_ttl, d.dest))
447     if d.type == "NS":
448         f.write("update %s %s %u NS %s\n" % (op, normalised_name, default_ttl, d.dest))
449     if opts.verbose:
450         f.write("show\n")
451     f.write("send\n")
452     f.close()
453
454     # Set a bigger MTU size to work around a bug in nsupdate's doio_send()
455     os.environ["SOCKET_WRAPPER_MTU"] = "2000"
456
457     global error_count
458     if ccachename:
459         os.environ["KRB5CCNAME"] = ccachename
460     try:
461         cmd = nsupdate_cmd[:]
462         cmd.append(tmpfile)
463         env = os.environ
464         if krb5conf:
465             env["KRB5_CONFIG"] = krb5conf
466         if ccachename:
467             env["KRB5CCNAME"] = ccachename
468         ret = subprocess.call(cmd, shell=False, env=env)
469         if ret != 0:
470             if opts.fail_immediately:
471                 if opts.verbose:
472                     print("Failed update with %s" % tmpfile)
473                 sys.exit(1)
474             error_count = error_count + 1
475             if opts.verbose:
476                 print("Failed nsupdate: %d" % ret)
477     except Exception, estr:
478         if opts.fail_immediately:
479             sys.exit(1)
480         error_count = error_count + 1
481         if opts.verbose:
482             print("Failed nsupdate: %s : %s" % (str(d), estr))
483     os.unlink(tmpfile)
484
485     # Let socket_wrapper set the default MTU size
486     os.environ["SOCKET_WRAPPER_MTU"] = "0"
487
488
489 def call_samba_tool(d, op="add", zone=None):
490     """call samba-tool dns to update an entry."""
491
492     assert(op in ["add", "delete"])
493
494     if (sub_vars['DNSFOREST'] != sub_vars['DNSDOMAIN']) and \
495        sub_vars['DNSFOREST'].endswith('.' + sub_vars['DNSDOMAIN']):
496         print "Refusing to use samba-tool when forest %s is under domain %s" \
497             % (sub_vars['DNSFOREST'], sub_vars['DNSDOMAIN'])
498
499     if opts.verbose:
500         print "Calling samba-tool dns for %s (%s)" % (d, op)
501
502     normalised_name = d.name.rstrip('.') + '.'
503     if zone is None:
504         if normalised_name == (sub_vars['DNSDOMAIN'] + '.'):
505             short_name = '@'
506             zone = sub_vars['DNSDOMAIN']
507         elif normalised_name == (sub_vars['DNSFOREST'] + '.'):
508             short_name = '@'
509             zone = sub_vars['DNSFOREST']
510         elif normalised_name == ('_msdcs.' + sub_vars['DNSFOREST'] + '.'):
511             short_name = '@'
512             zone = '_msdcs.' + sub_vars['DNSFOREST']
513         else:
514             if not normalised_name.endswith('.' + sub_vars['DNSDOMAIN'] + '.'):
515                 print "Not Calling samba-tool dns for %s (%s), %s not in %s" % (d, op, normalised_name, sub_vars['DNSDOMAIN'] + '.')
516                 return False
517             elif normalised_name.endswith('._msdcs.' + sub_vars['DNSFOREST'] + '.'):
518                 zone = '_msdcs.' + sub_vars['DNSFOREST']
519             else:
520                 zone = sub_vars['DNSDOMAIN']
521             len_zone = len(zone)+2
522             short_name = normalised_name[:-len_zone]
523     else:
524         len_zone = len(zone)+2
525         short_name = normalised_name[:-len_zone]
526
527     if d.type == "A":
528         args = [rpc_server_ip, zone, short_name, "A", d.ip]
529     if d.type == "AAAA":
530         args = [rpc_server_ip, zone, short_name, "AAAA", d.ip]
531     if d.type == "SRV":
532         if op == "add" and d.existing_port is not None:
533             print "Not handling modify of exising SRV %s using samba-tool" % d
534             return False
535             op = "update"
536             args = [rpc_server_ip, zone, short_name, "SRV",
537                     "%s %s %s %s" % (d.existing_weight,
538                                      d.existing_port, "0", "100"),
539                     "%s %s %s %s" % (d.dest, d.port, "0", "100")]
540         else:
541             args = [rpc_server_ip, zone, short_name, "SRV", "%s %s %s %s" % (d.dest, d.port, "0", "100")]
542     if d.type == "CNAME":
543         if d.existing_cname_target is None:
544             args = [rpc_server_ip, zone, short_name, "CNAME", d.dest]
545         else:
546             op = "update"
547             args = [rpc_server_ip, zone, short_name, "CNAME",
548                     d.existing_cname_target.rstrip('.'), d.dest]
549
550     if d.type == "NS":
551         args = [rpc_server_ip, zone, short_name, "NS", d.dest]
552
553     global error_count
554     try:
555         cmd = cmd_dns()
556         if opts.verbose:
557             print "Calling samba-tool dns %s -k no -P %s" % (op, args)
558         cmd._run("dns", op, "-k", "no", "-P", *args)
559     except Exception, estr:
560         raise
561         if opts.fail_immediately:
562             sys.exit(1)
563         error_count = error_count + 1
564         if opts.verbose:
565             print("Failed 'samba-tool dns' based update: %s : %s" % (str(d), estr))
566
567 def rodc_dns_update(d, t, op):
568     '''a single DNS update via the RODC netlogon call'''
569     global sub_vars
570
571     assert(op in ["add", "delete"])
572
573     if opts.verbose:
574         print "Calling netlogon RODC update for %s" % d
575
576     typemap = {
577         netlogon.NlDnsLdapAtSite       : netlogon.NlDnsInfoTypeNone,
578         netlogon.NlDnsGcAtSite         : netlogon.NlDnsDomainNameAlias,
579         netlogon.NlDnsDsaCname         : netlogon.NlDnsDomainNameAlias,
580         netlogon.NlDnsKdcAtSite        : netlogon.NlDnsInfoTypeNone,
581         netlogon.NlDnsDcAtSite         : netlogon.NlDnsInfoTypeNone,
582         netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
583         netlogon.NlDnsGenericGcAtSite  : netlogon.NlDnsDomainNameAlias
584         }
585
586     w = winbind.winbind("irpc:winbind_server", lp)
587     dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
588     dns_names.count = 1
589     name = netlogon.NL_DNS_NAME_INFO()
590     name.type = t
591     name.dns_domain_info_type = typemap[t]
592     name.priority = 0
593     name.weight   = 0
594     if d.port is not None:
595         name.port = int(d.port)
596     if op == "add":
597         name.dns_register = True
598     else:
599         name.dns_register = False
600     dns_names.names = [ name ]
601     site_name = sub_vars['SITE'].decode('utf-8')
602
603     global error_count
604
605     try:
606         ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
607         if ret_names.names[0].status != 0:
608             print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
609             error_count = error_count + 1
610     except RuntimeError, reason:
611         print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
612         error_count = error_count + 1
613
614     if error_count != 0 and opts.fail_immediately:
615         sys.exit(1)
616
617
618 def call_rodc_update(d, op="add"):
619     '''RODCs need to use the netlogon API for nsupdate'''
620     global lp, sub_vars
621
622     assert(op in ["add", "delete"])
623
624     # we expect failure for 3268 if we aren't a GC
625     if d.port is not None and int(d.port) == 3268:
626         return
627
628     # map the DNS request to a netlogon update type
629     map = {
630         netlogon.NlDnsLdapAtSite       : '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
631         netlogon.NlDnsGcAtSite         : '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
632         netlogon.NlDnsDsaCname         : '${NTDSGUID}._msdcs.${DNSFOREST}',
633         netlogon.NlDnsKdcAtSite        : '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
634         netlogon.NlDnsDcAtSite         : '_ldap._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
635         netlogon.NlDnsRfc1510KdcAtSite : '_kerberos._tcp.${SITE}._sites.${DNSDOMAIN}',
636         netlogon.NlDnsGenericGcAtSite  : '_gc._tcp.${SITE}._sites.${DNSFOREST}'
637         }
638
639     for t in map:
640         subname = samba.substitute_var(map[t], sub_vars)
641         if subname.lower() == d.name.lower():
642             # found a match - do the update
643             rodc_dns_update(d, t, op)
644             return
645     if opts.verbose:
646         print("Unable to map to netlogon DNS update: %s" % d)
647
648
649 # get the list of DNS entries we should have
650 if opts.update_list:
651     dns_update_list = opts.update_list
652 else:
653     dns_update_list = lp.private_path('dns_update_list')
654
655 if opts.update_cache:
656     dns_update_cache = opts.update_cache
657 else:
658     dns_update_cache = lp.private_path('dns_update_cache')
659
660 # use our private krb5.conf to avoid problems with the wrong domain
661 # bind9 nsupdate wants the default domain set
662 krb5conf = lp.private_path('krb5.conf')
663 os.environ['KRB5_CONFIG'] = krb5conf
664
665 file = open(dns_update_list, "r")
666
667 if opts.nosubs:
668     sub_vars = {}
669 else:
670     samdb = SamDB(url=lp.samdb_url(), session_info=system_session(), lp=lp)
671
672     # get the substitution dictionary
673     sub_vars = get_subst_vars(samdb)
674
675 # build up a list of update commands to pass to nsupdate
676 update_list = []
677 dns_list = []
678 cache_list = []
679 delete_list = []
680
681 dup_set = set()
682 cache_set = set()
683
684 rebuild_cache = False
685
686 # Add an NS line if asked to ...
687 if opts.add_ns:
688     if opts.use_file is None:
689         print "Option --add-ns can only be used with --use-file"
690         sys.exit(1)
691     else:
692         dns_list.append(parse_dns_line("NS ${DNSDOMAIN} ${HOSTNAME}", sub_vars))
693
694 try:
695     cfile = open(dns_update_cache, 'r+')
696 except IOError:
697     # Perhaps create it
698     cfile = open(dns_update_cache, 'w+')
699     # Open it for reading again, in case someone else got to it first
700     cfile = open(dns_update_cache, 'r+')
701 fcntl.lockf(cfile, fcntl.LOCK_EX)
702 for line in cfile:
703     line = line.strip()
704     if line == '' or line[0] == "#":
705         continue
706     c = parse_dns_line(line, {})
707     if c is None:
708         continue
709     if str(c) not in cache_set:
710         cache_list.append(c)
711         cache_set.add(str(c))
712
713 # read each line, and check that the DNS name exists
714 for line in file:
715     line = line.strip()
716     if line == '' or line[0] == "#":
717         continue
718     d = parse_dns_line(line, sub_vars)
719     if d is None:
720         continue
721     if d.type == 'A' and len(IP4s) == 0:
722         continue
723     if d.type == 'AAAA' and len(IP6s) == 0:
724         continue
725     if str(d) not in dup_set:
726         dns_list.append(d)
727         dup_set.add(str(d))
728
729 # now expand the entries, if any are A record with ip set to $IP
730 # then replace with multiple entries, one for each interface IP
731 for d in dns_list:
732     if d.ip != "$IP":
733         continue
734     if d.type == 'A':
735         d.ip = IP4s[0]
736         for i in range(len(IP4s)-1):
737             d2 = dnsobj(str(d))
738             d2.ip = IP4s[i+1]
739             dns_list.append(d2)
740     if d.type == 'AAAA':
741         d.ip = IP6s[0]
742         for i in range(len(IP6s)-1):
743             d2 = dnsobj(str(d))
744             d2.ip = IP6s[i+1]
745             dns_list.append(d2)
746
747 # now check if the entries already exist on the DNS server
748 for d in dns_list:
749     found = False
750     for c in cache_list:
751         if str(c).lower() == str(d).lower():
752             found = True
753             break
754     if not found:
755         rebuild_cache = True
756     if opts.all_names:
757         update_list.append(d)
758         if opts.verbose:
759             print "force update: %s" % d
760     elif not check_dns_name(d):
761         update_list.append(d)
762         if opts.verbose:
763             print "need update: %s" % d
764
765
766 for c in cache_list:
767     found = False
768     for d in dns_list:
769         if str(c).lower() == str(d).lower():
770             found = True
771             break
772     if found:
773         continue
774     rebuild_cache = True
775     if not opts.all_names and not check_dns_name(c):
776         continue
777     delete_list.append(c)
778     if opts.verbose:
779         print "need delete: %s" % c
780
781 if len(delete_list) == 0 and len(update_list) == 0 and not rebuild_cache:
782     if opts.verbose:
783         print "No DNS updates needed"
784     sys.exit(0)
785 else:
786     if opts.verbose:
787         print "%d DNS updates and %d DNS deletes needed" % (len(update_list), len(delete_list))
788
789 use_samba_tool = opts.use_samba_tool
790 use_nsupdate = opts.use_nsupdate
791 # get our krb5 creds
792 if len(delete_list) != 0 or len(update_list) != 0 and not opts.nocreds:
793     try:
794         creds = get_credentials(lp)
795     except RuntimeError as e:
796         ccachename = None
797
798         if sub_vars['IF_RWDNS_DOMAIN'] == "# ":
799             raise
800
801         if use_nsupdate:
802             raise
803
804         print "Failed to get Kerberos credentials, falling back to samba-tool: %s" % e
805         use_samba_tool = True
806
807
808 # ask nsupdate to delete entries as needed
809 for d in delete_list:
810     if d.rpc or (not use_nsupdate and use_samba_tool):
811         if opts.verbose:
812             print "update (samba-tool): %s" % d
813         call_samba_tool(d, op="delete", zone=d.zone)
814
815     elif am_rodc:
816         if d.name.lower() == domain.lower():
817             if opts.verbose:
818                 print "skip delete (rodc): %s" % d
819             continue
820         if not d.type in [ 'A', 'AAAA' ]:
821             if opts.verbose:
822                 print "delete (rodc): %s" % d
823             call_rodc_update(d, op="delete")
824         else:
825             if opts.verbose:
826                 print "delete (nsupdate): %s" % d
827             call_nsupdate(d, op="delete")
828     else:
829         if opts.verbose:
830             print "delete (nsupdate): %s" % d
831         call_nsupdate(d, op="delete")
832
833 # ask nsupdate to add entries as needed
834 for d in update_list:
835     if d.rpc or (not use_nsupdate and use_samba_tool):
836         if opts.verbose:
837             print "update (samba-tool): %s" % d
838         call_samba_tool(d, zone=d.zone)
839
840     elif am_rodc:
841         if d.name.lower() == domain.lower():
842             if opts.verbose:
843                 print "skip (rodc): %s" % d
844             continue
845         if not d.type in [ 'A', 'AAAA' ]:
846             if opts.verbose:
847                 print "update (rodc): %s" % d
848             call_rodc_update(d)
849         else:
850             if opts.verbose:
851                 print "update (nsupdate): %s" % d
852             call_nsupdate(d)
853     else:
854         if opts.verbose:
855             print "update(nsupdate): %s" % d
856         call_nsupdate(d)
857
858 if rebuild_cache:
859     print "Rebuilding cache at %s" % dns_update_cache
860     (file_dir, file_name) = os.path.split(dns_update_cache)
861     (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
862     wfile = os.fdopen(tmp_fd, 'a')
863     for d in dns_list:
864         if opts.verbose:
865             print "Adding %s to %s" % (str(d), file_name)
866         wfile.write(str(d)+"\n")
867     os.rename(tmpfile, dns_update_cache)
868 fcntl.lockf(cfile, fcntl.LOCK_UN)
869
870 # delete the ccache if we created it
871 if ccachename is not None:
872     os.unlink(ccachename)
873
874 if error_count != 0:
875     print("Failed update of %u entries" % error_count)
876 sys.exit(error_count)