Move dnspython to third_party.
[samba.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         if self.type == 'SRV':
143             if len(list) < 4:
144                 raise Exception("Invalid DNS entry %r" % string_form)
145             self.dest = list[2]
146             self.port = list[3]
147         elif self.type in ['A', 'AAAA']:
148             self.ip   = list[2] # usually $IP, which gets replaced
149         elif self.type == 'CNAME':
150             self.dest = list[2]
151         elif self.type == 'NS':
152             self.dest = list[2]
153         else:
154             raise Exception("Received unexpected DNS reply of type %s: %s" % (self.type, string_form))
155
156     def __str__(self):
157         if self.type == "A":
158             return "%s %s %s" % (self.type, self.name, self.ip)
159         if self.type == "AAAA":
160             return "%s %s %s" % (self.type, self.name, self.ip)
161         if self.type == "SRV":
162             return "%s %s %s %s" % (self.type, self.name, self.dest, self.port)
163         if self.type == "CNAME":
164             return "%s %s %s" % (self.type, self.name, self.dest)
165         if self.type == "NS":
166             return "%s %s %s" % (self.type, self.name, self.dest)
167
168
169 def parse_dns_line(line, sub_vars):
170     """parse a DNS line from."""
171     if line.startswith("SRV _ldap._tcp.pdc._msdcs.") and not samdb.am_pdc():
172         # We keep this as compat to the dns_update_list of 4.0/4.1
173         if opts.verbose:
174             print "Skipping PDC entry (%s) as we are not a PDC" % line
175         return None
176     subline = samba.substitute_var(line, sub_vars)
177     if subline == '' or subline[0] == "#":
178         return None
179     return dnsobj(subline)
180
181
182 def hostname_match(h1, h2):
183     """see if two hostnames match."""
184     h1 = str(h1)
185     h2 = str(h2)
186     return h1.lower().rstrip('.') == h2.lower().rstrip('.')
187
188
189 def check_dns_name(d):
190     """check that a DNS entry exists."""
191     normalised_name = d.name.rstrip('.') + '.'
192     if opts.verbose:
193         print "Looking for DNS entry %s as %s" % (d, normalised_name)
194
195     if opts.use_file is not None:
196         try:
197             dns_file = open(opts.use_file, "r")
198         except IOError:
199             return False
200
201         for line in dns_file:
202             line = line.strip()
203             if line == '' or line[0] == "#":
204                 continue
205             if line.lower() == str(d).lower():
206                 return True
207         return False
208
209     resolver = dns.resolver.Resolver()
210
211     try:
212         if getattr(d, 'nameservers', None):
213             resolver.nameservers = list(d.nameservers)
214         ans = resolver.query(normalised_name, d.type)
215     except dns.exception.DNSException:
216         if opts.verbose:
217             print "Failed to find DNS entry %s" % d
218         return False
219     if d.type in ['A', 'AAAA']:
220         # we need to be sure that our IP is there
221         for rdata in ans:
222             if str(rdata) == str(d.ip):
223                 return True
224     elif d.type == 'CNAME':
225         for i in range(len(ans)):
226             if hostname_match(ans[i].target, d.dest):
227                 return True
228     elif d.type == 'NS':
229         for i in range(len(ans)):
230             if hostname_match(ans[i].target, d.dest):
231                 return True
232     elif d.type == 'SRV':
233         for rdata in ans:
234             if opts.verbose:
235                 print "Checking %s against %s" % (rdata, d)
236             if hostname_match(rdata.target, d.dest):
237                 if str(rdata.port) == str(d.port):
238                     return True
239                 else:
240                     d.existing_port     = str(rdata.port)
241                     d.existing_weight = str(rdata.weight)
242
243     if opts.verbose:
244         print "Failed to find matching DNS entry %s" % d
245
246     return False
247
248
249 def get_subst_vars(samdb):
250     """get the list of substitution vars."""
251     global lp, am_rodc
252     vars = {}
253
254     vars['DNSDOMAIN'] = samdb.domain_dns_name()
255     vars['DNSFOREST'] = samdb.forest_dns_name()
256     vars['HOSTNAME']  = samdb.host_dns_name()
257     vars['NTDSGUID']  = samdb.get_ntds_GUID()
258     vars['SITE']      = samdb.server_site_name()
259     res = samdb.search(base=samdb.get_default_basedn(), scope=SCOPE_BASE, attrs=["objectGUID"])
260     guid = samdb.schema_format_value("objectGUID", res[0]['objectGUID'][0])
261     vars['DOMAINGUID'] = guid
262
263     vars['IF_DC'] = ""
264     vars['IF_RWDC'] = "# "
265     vars['IF_RODC'] = "# "
266     vars['IF_PDC'] = "# "
267     vars['IF_GC'] = "# "
268     vars['IF_RWGC'] = "# "
269     vars['IF_ROGC'] = "# "
270     vars['IF_DNS_DOMAIN'] = "# "
271     vars['IF_RWDNS_DOMAIN'] = "# "
272     vars['IF_RODNS_DOMAIN'] = "# "
273     vars['IF_DNS_FOREST'] = "# "
274     vars['IF_RWDNS_FOREST'] = "# "
275     vars['IF_R0DNS_FOREST'] = "# "
276
277     am_rodc = samdb.am_rodc()
278     if am_rodc:
279         vars['IF_RODC'] = ""
280     else:
281         vars['IF_RWDC'] = ""
282
283     if samdb.am_pdc():
284         vars['IF_PDC'] = ""
285
286     # check if we "are DNS server"
287     res = samdb.search(base=samdb.get_config_basedn(),
288                    expression='(objectguid=%s)' % vars['NTDSGUID'],
289                    attrs=["options", "msDS-hasMasterNCs"])
290
291     if len(res) == 1:
292         if "options" in res[0]:
293             options = int(res[0]["options"][0])
294             if (options & dsdb.DS_NTDSDSA_OPT_IS_GC) != 0:
295                 vars['IF_GC'] = ""
296                 if am_rodc:
297                     vars['IF_ROGC'] = ""
298                 else:
299                     vars['IF_RWGC'] = ""
300
301         basedn = str(samdb.get_default_basedn())
302         forestdn = str(samdb.get_root_basedn())
303
304         if "msDS-hasMasterNCs" in res[0]:
305             for e in res[0]["msDS-hasMasterNCs"]:
306                 if str(e) == "DC=DomainDnsZones,%s" % basedn:
307                     vars['IF_DNS_DOMAIN'] = ""
308                     if am_rodc:
309                         vars['IF_RODNS_DOMAIN'] = ""
310                     else:
311                         vars['IF_RWDNS_DOMAIN'] = ""
312                 if str(e) == "DC=ForestDnsZones,%s" % forestdn:
313                     vars['IF_DNS_FOREST'] = ""
314                     if am_rodc:
315                         vars['IF_RODNS_FOREST'] = ""
316                     else:
317                         vars['IF_RWDNS_FOREST'] = ""
318
319     return vars
320
321
322 def call_nsupdate(d, op="add"):
323     """call nsupdate for an entry."""
324     global ccachename, nsupdate_cmd, krb5conf
325
326     assert(op in ["add", "delete"])
327
328     if opts.verbose:
329         print "Calling nsupdate for %s (%s)" % (d, op)
330
331     if opts.use_file is not None:
332         try:
333             rfile = open(opts.use_file, 'r+')
334         except IOError:
335             # Perhaps create it
336             rfile = open(opts.use_file, 'w+')
337             # Open it for reading again, in case someone else got to it first
338             rfile = open(opts.use_file, 'r+')
339         fcntl.lockf(rfile, fcntl.LOCK_EX)
340         (file_dir, file_name) = os.path.split(opts.use_file)
341         (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
342         wfile = os.fdopen(tmp_fd, 'a')
343         rfile.seek(0)
344         for line in rfile:
345             if op == "delete":
346                 l = parse_dns_line(line, {})
347                 if str(l).lower() == str(d).lower():
348                     continue
349             wfile.write(line)
350         if op == "add":
351             wfile.write(str(d)+"\n")
352         os.rename(tmpfile, opts.use_file)
353         fcntl.lockf(rfile, fcntl.LOCK_UN)
354         return
355
356     normalised_name = d.name.rstrip('.') + '.'
357
358     (tmp_fd, tmpfile) = tempfile.mkstemp()
359     f = os.fdopen(tmp_fd, 'w')
360     if getattr(d, 'nameservers', None):
361         f.write('server %s\n' % d.nameservers[0])
362     if d.type == "A":
363         f.write("update %s %s %u A %s\n" % (op, normalised_name, default_ttl, d.ip))
364     if d.type == "AAAA":
365         f.write("update %s %s %u AAAA %s\n" % (op, normalised_name, default_ttl, d.ip))
366     if d.type == "SRV":
367         if op == "add" and d.existing_port is not None:
368             f.write("update delete %s SRV 0 %s %s %s\n" % (normalised_name, d.existing_weight,
369                                                            d.existing_port, d.dest))
370         f.write("update %s %s %u SRV 0 100 %s %s\n" % (op, normalised_name, default_ttl, d.port, d.dest))
371     if d.type == "CNAME":
372         f.write("update %s %s %u CNAME %s\n" % (op, normalised_name, default_ttl, d.dest))
373     if d.type == "NS":
374         f.write("update %s %s %u NS %s\n" % (op, normalised_name, default_ttl, d.dest))
375     if opts.verbose:
376         f.write("show\n")
377     f.write("send\n")
378     f.close()
379
380     global error_count
381     if ccachename:
382         os.environ["KRB5CCNAME"] = ccachename
383     try:
384         cmd = nsupdate_cmd[:]
385         cmd.append(tmpfile)
386         env = {}
387         if krb5conf:
388             env["KRB5_CONFIG"] = krb5conf
389         if ccachename:
390             env["KRB5CCNAME"] = ccachename
391         ret = subprocess.call(cmd, shell=False, env=env)
392         if ret != 0:
393             if opts.fail_immediately:
394                 if opts.verbose:
395                     print("Failed update with %s" % tmpfile)
396                 sys.exit(1)
397             error_count = error_count + 1
398             if opts.verbose:
399                 print("Failed nsupdate: %d" % ret)
400     except Exception, estr:
401         if opts.fail_immediately:
402             sys.exit(1)
403         error_count = error_count + 1
404         if opts.verbose:
405             print("Failed nsupdate: %s : %s" % (str(d), estr))
406     os.unlink(tmpfile)
407
408
409
410 def rodc_dns_update(d, t, op):
411     '''a single DNS update via the RODC netlogon call'''
412     global sub_vars
413
414     assert(op in ["add", "delete"])
415
416     if opts.verbose:
417         print "Calling netlogon RODC update for %s" % d
418
419     typemap = {
420         netlogon.NlDnsLdapAtSite       : netlogon.NlDnsInfoTypeNone,
421         netlogon.NlDnsGcAtSite         : netlogon.NlDnsDomainNameAlias,
422         netlogon.NlDnsDsaCname         : netlogon.NlDnsDomainNameAlias,
423         netlogon.NlDnsKdcAtSite        : netlogon.NlDnsInfoTypeNone,
424         netlogon.NlDnsDcAtSite         : netlogon.NlDnsInfoTypeNone,
425         netlogon.NlDnsRfc1510KdcAtSite : netlogon.NlDnsInfoTypeNone,
426         netlogon.NlDnsGenericGcAtSite  : netlogon.NlDnsDomainNameAlias
427         }
428
429     w = winbind.winbind("irpc:winbind_server", lp)
430     dns_names = netlogon.NL_DNS_NAME_INFO_ARRAY()
431     dns_names.count = 1
432     name = netlogon.NL_DNS_NAME_INFO()
433     name.type = t
434     name.dns_domain_info_type = typemap[t]
435     name.priority = 0
436     name.weight   = 0
437     if d.port is not None:
438         name.port = int(d.port)
439     if op == "add":
440         name.dns_register = True
441     else:
442         name.dns_register = False
443     dns_names.names = [ name ]
444     site_name = sub_vars['SITE'].decode('utf-8')
445
446     global error_count
447
448     try:
449         ret_names = w.DsrUpdateReadOnlyServerDnsRecords(site_name, default_ttl, dns_names)
450         if ret_names.names[0].status != 0:
451             print("Failed to set DNS entry: %s (status %u)" % (d, ret_names.names[0].status))
452             error_count = error_count + 1
453     except RuntimeError, reason:
454         print("Error setting DNS entry of type %u: %s: %s" % (t, d, reason))
455         error_count = error_count + 1
456
457     if error_count != 0 and opts.fail_immediately:
458         sys.exit(1)
459
460
461 def call_rodc_update(d, op="add"):
462     '''RODCs need to use the netlogon API for nsupdate'''
463     global lp, sub_vars
464
465     assert(op in ["add", "delete"])
466
467     # we expect failure for 3268 if we aren't a GC
468     if d.port is not None and int(d.port) == 3268:
469         return
470
471     # map the DNS request to a netlogon update type
472     map = {
473         netlogon.NlDnsLdapAtSite       : '_ldap._tcp.${SITE}._sites.${DNSDOMAIN}',
474         netlogon.NlDnsGcAtSite         : '_ldap._tcp.${SITE}._sites.gc._msdcs.${DNSDOMAIN}',
475         netlogon.NlDnsDsaCname         : '${NTDSGUID}._msdcs.${DNSFOREST}',
476         netlogon.NlDnsKdcAtSite        : '_kerberos._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
477         netlogon.NlDnsDcAtSite         : '_ldap._tcp.${SITE}._sites.dc._msdcs.${DNSDOMAIN}',
478         netlogon.NlDnsRfc1510KdcAtSite : '_kerberos._tcp.${SITE}._sites.${DNSDOMAIN}',
479         netlogon.NlDnsGenericGcAtSite  : '_gc._tcp.${SITE}._sites.${DNSFOREST}'
480         }
481
482     for t in map:
483         subname = samba.substitute_var(map[t], sub_vars)
484         if subname.lower() == d.name.lower():
485             # found a match - do the update
486             rodc_dns_update(d, t, op)
487             return
488     if opts.verbose:
489         print("Unable to map to netlogon DNS update: %s" % d)
490
491
492 # get the list of DNS entries we should have
493 if opts.update_list:
494     dns_update_list = opts.update_list
495 else:
496     dns_update_list = lp.private_path('dns_update_list')
497
498 if opts.update_cache:
499     dns_update_cache = opts.update_cache
500 else:
501     dns_update_cache = lp.private_path('dns_update_cache')
502
503 # use our private krb5.conf to avoid problems with the wrong domain
504 # bind9 nsupdate wants the default domain set
505 krb5conf = lp.private_path('krb5.conf')
506 os.environ['KRB5_CONFIG'] = krb5conf
507
508 file = open(dns_update_list, "r")
509
510 if opts.nosubs:
511     sub_vars = {}
512 else:
513     samdb = SamDB(url=lp.samdb_url(), session_info=system_session(), lp=lp)
514
515     # get the substitution dictionary
516     sub_vars = get_subst_vars(samdb)
517
518 # build up a list of update commands to pass to nsupdate
519 update_list = []
520 dns_list = []
521 cache_list = []
522 delete_list = []
523
524 dup_set = set()
525 cache_set = set()
526
527 rebuild_cache = False
528 try:
529     cfile = open(dns_update_cache, 'r+')
530 except IOError:
531     # Perhaps create it
532     cfile = open(dns_update_cache, 'w+')
533     # Open it for reading again, in case someone else got to it first
534     cfile = open(dns_update_cache, 'r+')
535 fcntl.lockf(cfile, fcntl.LOCK_EX)
536 for line in cfile:
537     line = line.strip()
538     if line == '' or line[0] == "#":
539         continue
540     c = parse_dns_line(line, {})
541     if c is None:
542         continue
543     if str(c) not in cache_set:
544         cache_list.append(c)
545         cache_set.add(str(c))
546
547 # read each line, and check that the DNS name exists
548 for line in file:
549     line = line.strip()
550     if line == '' or line[0] == "#":
551         continue
552     d = parse_dns_line(line, sub_vars)
553     if d is None:
554         continue
555     if d.type == 'A' and len(IP4s) == 0:
556         continue
557     if d.type == 'AAAA' and len(IP6s) == 0:
558         continue
559     if str(d) not in dup_set:
560         dns_list.append(d)
561         dup_set.add(str(d))
562
563 # now expand the entries, if any are A record with ip set to $IP
564 # then replace with multiple entries, one for each interface IP
565 for d in dns_list:
566     if d.ip != "$IP":
567         continue
568     if d.type == 'A':
569         d.ip = IP4s[0]
570         for i in range(len(IP4s)-1):
571             d2 = dnsobj(str(d))
572             d2.ip = IP4s[i+1]
573             dns_list.append(d2)
574     if d.type == 'AAAA':
575         d.ip = IP6s[0]
576         for i in range(len(IP6s)-1):
577             d2 = dnsobj(str(d))
578             d2.ip = IP6s[i+1]
579             dns_list.append(d2)
580
581 # now check if the entries already exist on the DNS server
582 for d in dns_list:
583     found = False
584     for c in cache_list:
585         if str(c).lower() == str(d).lower():
586             found = True
587             break
588     if not found:
589         rebuild_cache = True
590     if opts.all_names or not check_dns_name(d):
591         update_list.append(d)
592
593 for c in cache_list:
594     found = False
595     for d in dns_list:
596         if str(c).lower() == str(d).lower():
597             found = True
598             break
599     if found:
600         continue
601     rebuild_cache = True
602     if not opts.all_names and not check_dns_name(c):
603         continue
604     delete_list.append(c)
605
606 if len(delete_list) == 0 and len(update_list) == 0 and not rebuild_cache:
607     if opts.verbose:
608         print "No DNS updates needed"
609     sys.exit(0)
610
611 # get our krb5 creds
612 if len(delete_list) != 0 or len(update_list) != 0:
613     if not opts.nocreds:
614         get_credentials(lp)
615
616 # ask nsupdate to delete entries as needed
617 for d in delete_list:
618     if am_rodc:
619         if d.name.lower() == domain.lower():
620             continue
621         if not d.type in [ 'A', 'AAAA' ]:
622             call_rodc_update(d, op="delete")
623         else:
624             call_nsupdate(d, op="delete")
625     else:
626         call_nsupdate(d, op="delete")
627
628 # ask nsupdate to add entries as needed
629 for d in update_list:
630     if am_rodc:
631         if d.name.lower() == domain.lower():
632             continue
633         if not d.type in [ 'A', 'AAAA' ]:
634             call_rodc_update(d)
635         else:
636             call_nsupdate(d)
637     else:
638         call_nsupdate(d)
639
640 if rebuild_cache:
641     (file_dir, file_name) = os.path.split(dns_update_cache)
642     (tmp_fd, tmpfile) = tempfile.mkstemp(dir=file_dir, prefix=file_name, suffix="XXXXXX")
643     wfile = os.fdopen(tmp_fd, 'a')
644     for d in dns_list:
645         wfile.write(str(d)+"\n")
646     os.rename(tmpfile, dns_update_cache)
647 fcntl.lockf(cfile, fcntl.LOCK_UN)
648
649 # delete the ccache if we created it
650 if ccachename is not None:
651     os.unlink(ccachename)
652
653 if error_count != 0:
654     print("Failed update of %u entries" % error_count)
655 sys.exit(error_count)