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